链接
http://ac.jobdu.com/problem.php?pid=1172
-
题目描述:
-
哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和。
-
输入:
-
输入有多组数据。
每组第一行输入一个数n,接着输入n个叶节点(叶节点权值不超过100,2<=n<=1000)。
-
输出:
-
输出权值。
-
样例输入:
-
5 1 2 2 5 9
-
样例输出:
-
37
使用最小堆,每次弹出权值两个最小的节点求权值然后将两者之和压入队列。
优先队列的函数
empty() 如果队列为空返回真
pop() 删除对顶元素
push() 加入一个元素
size() 返回优先队列中拥有的元素个数
top() 返回优先队列对顶元素
默认的是大根堆
priority_queue<
int
>q1;
定义int类型的小根堆
priority_queue<int,vector<int>,greater<int> >q;
ac代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >q;
int T;
while(cin>>T)
{
int weight1,weight2;
long long result=0;
int temp;
for(int i=0; i<T; i++)
{
scanf("%d",&temp);
q.push(temp);
}
while(!q.empty())
{
weight1 = q.top();
result += weight1;
q.pop();
if(!q.empty())
{
weight2 = q.top();
result += weight2;
q.pop();
q.push(weight1+weight2);
}
else
result -= weight1;
}
printf("%d\n",result);
}
return 0;
}