Solution: Huffman

Description Title
Huffman tree, a first input line number n, the number of the leaf node. These need to generate the Huffman tree leaf node, the concept of the Huffman tree, the nodes which have the right value, i.e. weight, title product of the output value and the required weights and all nodes.

Enter
input multiple sets of data.
The first input line of each group a number n, then n to leaf nodes (leaf nodes weight 100,2 <= n does not exceed <= 1000).

Output
output weights.

Sample input
2
2. 8
. 3
. 5. 11 30
Sample Output
10
62 is
ideas: analog, preferably using a priority queue

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	int n;
	while(cin>>n)
	{
		priority_queue<int,vector<int>,greater<int> >q;
		int num;
		for(int i=0;i<n;i++)
		{
			cin>>num;q.push(num);
		}
		int sum=0;
		int a,b;
		while(q.size()>=2)
		{
			a=q.top();q.pop();
			b=q.top();q.pop();
			q.push(a+b);sum+=(a+b);
		}
		cout<<sum<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43540515/article/details/91869541