Solve the problem of the oj user tree by learning priority_queue and ojpriority_queue.
PS. To learn priority_queue, click the link at the end of the article. This article uses priority_queue to solve the problem of the Harman tree.
Postgraduate test:
Harman tree
Description:
The first line of the Heman tree is the number n, indicating the number of leaf nodes. We need to use these leaf nodes to generate a user-defined tree. According to the concept of the User-Defined tree, these nodes have the right value, that is, weight. The question needs to output the sum of the values of all nodes and their weights.
Input:
Multiple groups of data are input.
Enter n numbers for the first row of each group, and then enter n leaf nodes (the weight of leaf nodes cannot exceed 1000, 2 <= n <= ).
Output:
Output weight.
Sample input:
5
1 2 2 5 9
Sample output: 37
--------------------- Split line -------------
Solution of a person on the 9du oj:
Language: C
# Include <functional> # include <stdio. h ># include <queue> using namespace std; priority_queue <int, vector <int>, greater <int> Q; int main () {// program Harman tree int n, ans = 0; while (scanf ("% d", & n )! = EOF) {while (Q. empty () = false) Q. pop (); for (int I = 0; I <n; I ++) {int x; scanf ("% d", & x); Q. push (x);} ans = 0; while (Q. size ()> 1) {int a = Q. top (); Q. pop (); int B = Q. top (); Q. pop (); ans = ans + a + B; Q. push (a + B);} printf ("% d \ n", ans);} return 0 ;}
The above Code uses priority_queue to solve the problem.
Search for priority_queue online, see a learning post, link http://www.cnblogs.com/flyoung2008/articles/2136485.html
Benefit from this.