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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值