swustoj merge fruit

In an orchard, Duoduo has already knocked down all the fruits, and divided them into different piles according to the different types of fruits. Duoduo decided to combine all the fruits into a pile. Every time you merge, Duoduo can merge two piles of fruits together, and the stamina consumed is equal to the sum of the weights of the two piles of fruits. It can be seen that after all the fruits are merged n-1 times, there is only one pile left. The total stamina consumed by Duoduo when merging fruits is equal to the sum of the stamina consumed by each merging. Because it takes a lot of effort to bring these fruits home, Duoduo should save as much energy as possible when combining the fruits. Assuming that each fruit has a weight of 1, and the number of types of fruit and the number of each type of fruit are known, your task is to design a combined order scheme to minimize the physical effort of Duoduo, and output the minimum physical effort value. For example, there are 3 kinds of fruit, the number is 1, 2, 9. You can merge 1 and 2 piles first, the number of new piles is 3, and the stamina consumption is 3. Then, merge the new pile with the original third pile, and get a new pile, the number is 12, and the stamina is 12. So the total consumption of physical strength = 3 + 12 = 15. It can be proved that 15 is the minimum physical energy consumption value.

enter

 
  

The input consists of two lines, the first line is an integer n (1<=n<=10000), which represents the number of kinds of fruits. The second line contains n integers, separated by spaces, the ith integer ai (1<=ai<=20000) is the number of the ith fruit.

output

 
  

The output consists of one line containing only one integer, the minimum physical effort value. The input data guarantees that this value is less than 2^31.

sample input

3
1 2 9

Sample output

15
/*
answer:
Each time the two piles of the current minimum number of fruits are merged with the minimum cost,
So lazy to use the STL priority queue directly.
*/
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<algorithm>
#include<cmath>
#include<string>
#include<string.h>
using namespace std;
const int INF = 0x3f3f3f3f;
int dp[1005][1005];

struct cmp {
	bool operator () (int x, int y) {
		return x > y;
	}
};
intmain()
{
	priority_queue<int,vector<int>,cmp>q;
	int n;
	while (cin >> n) {
		int a;
		for (int i = 0;i < n;i++) {
			scanf("%d", &a);
			q.push(a);
		}
		int years = 0;
		while (q.size()>=2) {
			int tt = q.top ();
			q.pop();
			int bb = q.top();
			q.pop();
			int sum= tt + bb;
			ans += sum
			q.push(sum);
		}
		printf("%d\n", ans);
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325668878&siteId=291194637