7-11 哈夫曼树 (25 分)
哈夫曼树,第一行输入一个数n,表示叶结点的个数。
需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出哈夫曼树的带权路径长度(WPL)。
输入格式:
第一行输入一个数n,第二行输入n个叶结点(叶结点权值不超过1000,2<=n<=1000)。
输出格式:
在一行中输出WPL值。
输入样例:
5
1 2 2 5 9
输出样例:
37
上代码:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int Data;
friend bool operator<(struct Node nod1,struct Node nod2){
return nod1.Data>nod2.Data;
}
};
int main()
{
priority_queue<Node> que;
int N;
cin>>N;
struct Node arr[N];
int weight;
for(int i=0; i<N; i++)
{
cin>>weight;
arr[i].Data=weight;
que.push(arr[i]);
}
int sum=0;
for(int i=0;i<N-1;i++){
int temp1=que.top().Data;
que.pop();
int temp2=que.top().Data;
que.pop();
int newNode=0;
newNode=temp1+temp2;
Node key;key.Data=newNode;
sum=sum+newNode;
que.push(key);
if(que.size()==1){
cout<<sum<<endl;
break;
}
}
return 0;
}