poj 3253STL建立哈弗曼树

题意:给你n块长度已知的木板,已知FJ每次能连接两个木板成为一个新的木板,新的木板长度为两块木板之和。问FJ把n块木板连接起来成最后的一块木板的长度最小是多少?

思路:基础的haffman树。用优先队列去做,要记住haffman几段关键的代码。

还是stl写的猛!!!
这个题目倒不是很难(毕竟有discuss,呵呵),就看成赫夫曼树,然后求所有非叶子节点的总和就行了。不过看算法导论上将建立赫夫曼树要用到优先级队列,这个我还真懒的写,呵呵,所以就现学的优先队列。

代码如下:

#include <iostream>
#include <queue>
using namespace std;
struct node
{
	__int64 w;
	bool operator<(const node &a)const
	{
		return w>a.w;
	}
}tmp;

int main()
{
	int n;
	cin>>n;
	priority_queue<node> que;
	for (int i=0;i<n;i++)
	{
		scanf("%d",&tmp.w);
		que.push(tmp);
	}
	__int64 ans=0;
	while (que.size()>1)
	{
		int a,b;
		a=que.top().w;
		que.pop();
		b=que.top().w;
		que.pop();
		tmp.w=a+b;
		que.push(tmp);
		ans+=tmp.w;
	}
	printf("%I64d\n",ans);
	return 0;
	
}

 

    原文作者:哈夫曼树
    原文地址: https://blog.csdn.net/kaiweisun/article/details/84056500
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞