2014-05-03 21:57
原题:
Many sticks with length, every time combine two, the cost is the sum of two sticks' length. Finally, it will become a stick, what's the minimum cost?
题目:有很多根长度不同的棍子,每次选择其中两根拼起来,每次拼接的代价为两木棍长度之和。问把所有棍子拼成一根最少需要花多大代价。
解法:描述这么麻烦,还不如直接问哈夫曼编码呢。根据贪婪原则,每次选取长度最短的两个木棍即可。用小顶堆可以持续进行这个过程,直到只剩一根木棍为止。由于单个堆操作是对数级的,所以算法总体复杂度是O(n * log(n)),空间复杂度为O(n)。仿函数greater和less,对应于小顶堆和大顶堆。起初我经常搞反,时间长了就记住了。
代码:
// http://www.careercup.com/question?id=4557716425015296
#include <queue>
#include <vector>
using namespace std; template <class T>
struct greater {
bool operator () (const T &x, const T &y) {
return x > y;
};
}; class Solution {
public:
int minimalLengthSum(vector<int> &sticks) {
int i, n;
int sum;
int num1, num2; sum = ;
n = (int)sticks.size();
for (i = ; i < n; ++i) {
pq.push(sticks[i]);
} for (i = ; i < n - ; ++i) {
num1 = pq.top();
pq.pop();
num2 = pq.top();
pq.pop();
sum += num1 + num2;
pq.push(num1 + num2);
} while (!pq.empty()) {
pq.pop();
} return sum;
};
private:
// min heap
priority_queue<int, vector<int>, greater<int> > pq;
};