herrDeng網內搜尋

自訂搜尋

Ads

2024年2月15日 星期四

C++, python貪婪演算解多邊形問題Leetcode 2971 Find Polygon With the Largest Perimeter


C++, python貪婪演算解多邊形問題Leetcode 2971  Find Polygon With the Largest Perimeter
程式實作不難,用貪婪演算即可,有人知其然不知所以然,貪婪演算是否可用是需要數學證明的,下面有一個用make_heap的解答,保留在此
----
It is not difficult to implement the program, just use greedy algorithm. Some people know it but don’t know why. Whether greedy algorithm can be used needs mathematical proof.
  1. #pragma GCC optimize("O3", "unroll-loops")
  2. class Solution {
  3. public:
  4. static long long largestPerimeter(vector<int>& nums) {
  5. int n=nums.size();
  6. long long perimeter=accumulate(nums.begin(), nums.end(), 0LL);
  7. make_heap(nums.begin(), nums.end());
  8. for(int i=n-1; i>=2; i--){
  9. pop_heap(nums.begin(), nums.end());
  10. int largest=nums.back();
  11. nums.pop_back();
  12. if (largest<perimeter-largest) return perimeter;
  13. perimeter-=largest;
  14. }
  15. return -1;
  16. }
  17. };
  18.  
  19.  
  20. auto init = []()
  21. {
  22. ios::sync_with_stdio(0);
  23. cin.tie(0);
  24. cout.tie(0);
  25. return 'c';
  26. }();

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章