您的位置:首页 > 其它

UVA 10954 Add All

2017-08-11 21:57 405 查看
题意:有n个数的集合S,每次可以从S中删除两个数,然后把它们的和放回集合,直到剩下最后一个数。每次操作的开销等于删除的两个数的和,求最小总开销

解题思路:优先队列.Huffman编码的建立过程,但是因为n比较小,所以可以直接用优先队列实现。每次都将最小的两个数相加然后再压入队列,直到剩下最后一个数

代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <queue>
using namespace std;

int main()
{
int n,x;
while(cin>>n&&n)
{
priority_queue<int,vector<int>,greater<int> > q;//数小的优先级大
for(int i=0;i<n;i++)
{
cin>>x;
q.push(x);
}
int ans=0;
while(q.size()>1)
{
int a=q.top();q.pop();
int b=q.top();q.pop();
ans+=a+b;
q.push(a+b);
}
cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: