Solve the problem of the oj user tree by learning priority_queue and ojpriority_queue.

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.