NYoj 55 Xiao Ming (STL), nyoj55stl
Lazy Xiao Ming Time Limit: 3000 MS | memory limit: 65535 KB difficulty: 3
-
Description
-
James really wants to eat fruit, and the fruit of the orchard is ripe. In the orchard, James has laid down all the fruits and divided them into different heaps based on different types of fruits. James decided to combine all the fruits into a pile. James was too lazy. In order to save his effort, James began to think about the following ideas:
For each merge, James can combine the two fruits, and the physical strength consumed is equal to the sum of the weights of the two fruits. It can be seen that after all the fruits have been merged for n-1 times, there is only one pile left. The total physical strength consumed by James in merging results is the sum of physical strength consumed by each merge.
Because we have to make great effort to move these fruits back home, James should try to save as much effort as possible when merging the fruits. Assuming that each fruit has a weight of 1 and the number of known fruit types and the number of each fruit, your task is to design a combined sequence scheme to minimize James's physical strength, and output the minimum physical labor consumption value.
For example, there are three fruit types in sequence: 1, 2, and 9. You can merge 1 and 2 heaps first. The number of new heaps is 3, and the physical strength is 3. Next, merge the new heap with the original third heap and obtain the new heap. The number is 12, which consumes 12 resources. Therefore, James spent a total of 3 + 12 = 15. It can prove that 15 is the minimum physical labor cost.
-
Input
-
Enter the integer N (0 <N <= 10) in the first line to indicate the number of test data groups. Next, each group of test data input contains two rows. The first row is an integer n (1 <= n <= 12000), indicating the number of fruit types. The second line contains n integers separated by spaces. the I-th integer ai (1 <= ai <= 20000) is the number of fruit I.
-
Output
-
The output of each group of test data includes one row, which contains only one integer, that is, the minimum physical consumption value.
-
Sample Input
-
13 1 2 9
-
Sample output
-
15
Idea: select the two with the least number in the current heap and merge them...
Priority_queue
Code:
#include <iostream>#include <cstdio>#include <vector>#include <queue>#include <algorithm>#define LL long longconst int M = 100;using namespace std;struct cmp{bool operator ()(int &a, int &b){return a > b; //×îСֵÓÅÏÈ }};struct node{int x;bool operator < (const node &a) const {return x > a.x; // ×îСֵÓÅÏÈ }}; int main(){int t, n, s[M];cin >> t;priority_queue <int, vector<int>, cmp> q;while(t --){while(!q.empty()) q.pop();cin >> n;int i, temp;for(i = 0; i < n; ++ i){cin >> temp;q.push(temp);}LL sum = 0;while(q.size() > 1){int temp1 = q.top(); q.pop();int temp2 = q.top(); q.pop();//cout << temp1 << " " << temp2 << endl;temp = temp1+temp2;sum += temp; q.push(temp);}cout << sum << endl;}return 0;}