poj 3253 哈夫曼思想 优先队列实现

http://poj.org/problem?id=3253

这两天都没怎么写代码,因为数学拉的太多了。。。期中考来了。。 今天看了一篇文章,又想起这题,就跑来看看,发现之前居然并没有写题解。。。

思路,每个木板的开销应该是木板的长度乘以节点的深度。那么就是最短的板应该是深度最大的节点之一,每次将最短的和次短的合并起来就是当前最小的开销,一直加起来直到所有木板最后合并成一个木板。

代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
#define M 20009
#define INF 0x3f3f3f3f
typedef long long ll;
int l[M];
int cmp(int a,int b)
{
    return a < b;
}
int main()
{
    int n;
    while(scanf("%d",&n)==1)
    {
        priority_queue <int , vector<int> , greater<int> > q;
        for(int i = 0;i < n;i++)
        {
            scanf("%d",&l[i]);
            q.push(l[i]);
        }
        ll ans = 0;
        while(q.size()>1)
        {
            int t = q.top();
            q.pop();
            t += q.top();
            q.pop();
            ans += t;
            q.push(t);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(poj 3253 哈夫曼思想 优先队列实现)