题目链接:http://poj.org/problem?id=3253
思路:
题目与哈夫曼编码原理相同,使用优先队列与贪心思想;读入数据在优先队列中,弹出两个数计算它们的和,再压入队列中;
代码:
#include <iostream> #include <queue> using namespace std; struct cmp { bool operator() (long long a, long long b) { return a > b; } }; int main() { priority_queue<long long, vector<long long>, cmp> Q; long long n, ans = 0; cin >> n; for (int i = 0; i < n; ++i) { long long num; cin >> num; Q.push(num); } long long a, b; while (Q.size() != 1) { a = Q.top(); Q.pop(); b = Q.top(); Q.pop(); ans += a + b; Q.push(a + b); } cout << ans << endl; return 0; }
时间: 2024-12-13 03:20:02