Given the node weights, find the weighted path length sum of the Huffman tree

1. Huffman tree concept

In a tree, the path from any node to another is called a path, the number of edges contained in the path is called the length of the path, and the value that each node carries is a weight. The length of the path from the root node to the leaf node is multiplied by the weight of the leaf node, and the obtained value is the weighted path length of the node. The sum of the weighted path lengths of all leaf nodes in the tree is called the weighted path of the tree. length and. Given N nodes and their weights, the weighted path length and the smallest binary tree constructed with these N nodes as leaf nodes is the Huffman tree.

2. C language implements a given node to find the weighted path length sum of the Huffman tree

Huffman tree weighted path length and solution algorithm:

(1) All node weights are put into the set K, and the elements in K are always sorted from small to large (using the priority queue priority_queue).

(2) If the number of nodes in K is not less than 1, add the first two elements a and b, and pop the first two elements a and b, and insert the resulting sum into the set K (the order of elements in K remains unchanged after insertion From small to large); if the number of nodes in K is only 1, this is the weight of the root node.

(3) The weights of all intermediate nodes are added (that is, all a+b are summed), that is, the sum of the weighted path lengths of the desired Huffman tree (based on (path length * weight) The formula for summing is easy roll out)

Note: Using the priority queue, that is, the heap data structure, allows us to take out the smallest first two elements a, b in the set with O(logn) time complexity. For the specific principle, you can refer to the relevant knowledge of the heap structure.

#include<queue>
#include<functional>
priority_queue<int, vector<int>, greater<int>> Q;
int main() {
	int n;
	while (scanf_s("%d", &n) != EOF) {
		while (!Q.empty()) Q.pop();
		for (int i = 0; i < n; i++) {
			int tmp;
			scanf_s("%d", &tmp);
			Q.push(tmp);
		}
		int ans = 0;
		while(Q.size()>1){
		
				int a, b;
				a = Q.top();
				Q.pop();
				b = Q.top();
				Q.pop();
				ans += (a + b);
				Q.push(a + b);
		}
		printf("%d", ans);
	}
	return 0;
}


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326698840&siteId=291194637