UVA10954 哈夫曼编码

来源:互联网 发布:米内数据库 编辑:程序博客网 时间:2024/05/22 02:47


【分析】 这题没难度,就是哈夫曼编码的题。思想是贪心,用小根堆维护。不过我学习的重点是使用c++ STL的优先队列,以及如何自定义重载运算符。感觉STL真心实用且方便。

#include <cstdio>#include <queue>#include <cmath>using namespace std;typedef long long ll;int n;ll ans;struct cmp{   bool operator () (ll &a, ll &b){        return a>b;   }};priority_queue<ll,vector<ll>,cmp>que;void init(){    ll x;    while (!que.empty()) que.pop();    for (int i=0; i<n; i++) {        scanf("%lld",&x);        que.push(x);    }}void cnt(){   ans = 0;   ll tmp;   while (que.size()>1){       tmp = que.top();       que.pop();       tmp += que.top();       que.pop();       que.push(tmp);       ans += tmp;   }}int main(){    while (scanf("%d",&n) && n){        init();        cnt();        printf("%lld\n",ans);    }    return 0;}