TOJ-3488(哈夫曼)

3488.   Stones II
Time Limit: 2.0 Seconds   Memory Limit: 65536K
Total Runs: 2022   Accepted Runs: 626



Given n piles of stones, now we want to combine them into one pile. In order to finish this job, first we can select two piles arbitrarily, combine them into one; then select two piles from the remaining piles arbitrarily, combine them into one pile, and so on .. until there is only one pile. When we combine two piles, we need to cost some energy, and the cost is related to the sum of the number of stones in both pile. That is to say: If we combine two piles of the size 3 and 5, the energy cost is 8. Now our task is: given the size of the n piles, colculate how much energy we need to finish the job at least?

Input

The first line of the input is a single integer t, representing the number of test cases. The 2i-th and the 2i+1 -th lines describe the i-th test case. The 2i-th line gives the integer n, then the 2i+1 -th line gives n integers - the size of each pile. (0 < n ≤ 100000, and the size of each pile is no more than 100).

Output

For each test cases, output a single integer: the minmun energy we should cost.

Sample Input

1
4
5 9 6 3

Sample Output

45


题意:有n堆石子,每堆有一个重量,每次合并2堆石子消耗的能量等于两堆石子的重量和。求将n堆石子合并成一堆的最小消耗能量。
思路:哈夫曼,每次挑质量小的两堆进行合并。

 1 #include <iostream>
 2 #include <queue>
 3 using namespace std;
 4 int main()
 5 {
 6     priority_queue<int, vector<int>, greater<int> > q;
 7     int t, n, num;
 8     cin >> t;
 9     while(t--){
10         cin >> n;
11         while(n--){
12             cin >> num;
13             q.push(num);
14         }
15         long long result = 0;
16         while(q.size() > 1){
17             int num1 = q.top();
18             q.pop();
19             int num2 = q.top();
20             q.pop();
21             int sum = num1 + num2;
22             result += sum;
23             q.push(sum);
24         }
25         if(!q.empty())
26             cout << result << endl;
27         else
28             cout << 0 << endl;
29         while(q.size())
30             q.pop();
31     }
32     return 0;
33 }

 

 
posted @ 2016-02-23 14:29  喷水小火龙  阅读(75)  评论(0)    收藏  举报