poj 3253 哈夫曼贪心

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

题意:

FJ需要修补牧场的围栏,他需要 N 块长度为 Li 的木头(N planks of woods)。开始时,FJ只有一块无限长的木板,因此他需要把无限长的木板锯成 N 块长度为 Li 的木板,Farmer Don提供FJ锯子,但必须要收费的,收费的标准是对应每次据出木块的长度,比如说测试数据中 5 8 8,一开始,FJ需要在无限长的木板上锯下长度 21 的木板(5+8+8=21),第二次锯下长度为 5 的木板,第三次锯下长度为 8 的木板,至此就可以将长度分别为 5 8 8 的木板找出

 题解:把分块模拟成二叉树的形式,可以发现每个叶子节点的贡献和哈夫曼距离是一样的。问题的最优解是长度越小的叶子节点度数越大,哈夫曼编码思想咯。

ac代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
int main()
{
    int n;
    scanf("%d",&n);
    priority_queue<ll,vector<ll>,greater<ll> > q; //
    for(int i=1;i<=n;i++)
    {
        ll x;
        scanf("%lld",&x);
        q.push(x);
    }
    ll ans=0;
    while(!q.empty())
    {
        ll temp=q.top();
       // cout<<temp<<endl;
        q.pop();
        ll temp1=0;
        if(!q.empty())
        {
            temp1=q.top();
            q.pop();
            ll zz=temp1+temp;
            q.push(zz);
            ans+=(temp+temp1);
        }
    }
    cout<<ans<<endl;
    return 0;
}
原文地址:https://www.cnblogs.com/z1141000271/p/7426867.html