http://acm.bit.edu.cn/mod/programming/view.php?a=506

经教主的指导+自己的研究,终于搞懂这道题了。。。

赫夫曼树(最优二叉树)

构造 最优二叉树,求树的带全路径长度


#include<stdio.h>
#include<string.h>
#include<queue>
#include<functional>
using namespace std;

int main()
{
	int i,j,k;
	int t;
	scanf("%d",&t);
	priority_queue<double,vector<double>,greater<double> > q;  //注意和下面的写法,有个空格的区别,这么写就是对的
	//priority_queue<double,vector<double>,greater<double>> q;  这么写就编译不了。。
	while(t--)
	{
		int n;
		while(!q.empty())
			q.pop();
		scanf("%d",&n);
		for(i=0;i<n;i++)
		{
			double temp;
			scanf("%lf",&temp);
			q.push(temp);
		}
		double ans=0;
		while(q.size()!=1)
		{
			double t1,t2;
			t1=q.top(),q.pop();
			t2=q.top(),q.pop();
			ans+=(t1+t2);
			q.push(t1+t2);
		}
		if(n==1)
			printf("%.2lf\n",q.top());
		else
			printf("%.2lf\n",ans);
	}
}