优先队列/POJ3253,哈夫曼树(求最小木板分割费用)

描述:一个需要 9 10 11三块木板,现在他有9+10+11长度的木板,但是分割L长度的木板费用就是L,因此求怎么分割费用最小

算法:构造哈夫曼树,队列中取出最小的两个数放在底层,它们的和入队,如此反复;可以利用优先队列priority_queue

优先队列priority_queue默认大的数先出队,因此需要重载小于号

Sample Input
3
8
5
8

Sample Output
34

Hint
He wants to cut a board of length 21 into pieces of lengths 8, 5, and 8. 
The original board measures 8+5+8=21. The first cut will cost 21, and should be used to cut the board into pieces measuring 13 and 8. The second cut will cost 13, and should be used to cut the 13 into 8 and 5. This would cost 21+13=34. If the 21 was cut into 16 and 5 instead, the second cut would cost 16 for a total of 37 (which is more than 34).

#include<iostream>
#include<queue>
using namespace std;

struct node
{
    __int64 w;
    bool operator <(node b)const
    {return w>b.w;}
}tmp;
int n;
int main()
{
    int i;
    scanf("%d",&n);
    priority_queue<node>q;
    for(i=1;i<=n;i++)
    {
        scanf("%lld",&tmp.w);
        q.push(tmp);
    }
    __int64 ans=0;
    while(q.size()>1)
    {
        node a=q.top();q.pop();
        node b=q.top();q.pop();
        a.w+=b.w;
        ans+=a.w;
        q.push(a);
    }
    printf("%lld\n",ans);
	return 1;
}
posted on 2011-06-04 10:43  yangyh  阅读(487)  评论(0编辑  收藏  举报