poj 3053 Fence Repair(优先队列)

时间:2023-02-04 10:42:28

题目链接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 = ; cin >> n;
for (int i = ; i < n; ++i)
{
long long num; cin >> num;
Q.push(num);
} long long a, b;
while (Q.size() != )
{
a = Q.top(); Q.pop();
b = Q.top(); Q.pop();
ans += a + b;
Q.push(a + b);
} cout << ans << endl; return ;
}