篱笆修理(Fence Repair) 堆(heap) 代码(C++)
本文地址: http://blog.csdn.net/caroline_wendy
题目参考: http://blog.csdn.net/caroline_wendy/article/details/37911157
本题比较简单, 直接使用堆(heap)选取两个最小的值, 合并再放入堆, 最后求出和.
比起贪婪算法O(n^2), 时间复杂度O(nlogn).
代码:
/* * main.cpp * * Created on: 2014.7.20 * Author: spike */ /*eclipse cdt, gcc 4.8.1*/ #include <stdio.h> #include <queue> #include <vector> #include <functional> using namespace std; class Program { static const int MAX_N = 100; int N=3, L[MAX_N] = {8,5,8}; public: void solve() { int ans = 0; priority_queue<int, vector<int>, greater<int>> que; for (int i=0; i<N; i++) { que.push(L[i]); } while (que.size() > 1) { int l1, l2; l1 = que.top(); que.pop(); l2 = que.top(); que.pop(); ans += l1+l2; que.push(l1+l2); } printf("result = %d\n", ans); } }; int main(void) { Program iP; iP.solve(); return 0; }
输出:
result = 34
时间: 2024-10-11 05:45:03