UVA 10954 Add All(Huffman编码)

来源:互联网 发布:大数据医疗公司 编辑:程序博客网 时间:2024/05/20 11:22

题意:有n个(n<=5000)个数的集合S,每次可以从S中删除两个数,然后把它们的和放回集合,直到剩下一个数;每次操作的开销等于删除的两个数之和,求最小的总开销。所有数均小于10^5.

分析:从题意可以看出这是一个Huffman编码的问题。

AC代码:

#include<cstdio>#include<cstring>#include<queue>using namespace std;typedef long long LL;int main(){int N;while(scanf("%d",&N)==1 && N){priority_queue<int,vector<int>,greater<int> > q;for(int i = 0; i < N; i++){        int t;        scanf("%d",&t);        q.push(t);}LL tot = 0;for(int i = 0; i < N-1; i++){           int t = 0;           t += q.top();           q.pop();           t += q.top();   q.pop();   q.push(t);   tot += t; }printf("%lld\n",tot);}return 0;}




原创粉丝点击