Merge Fruit C++ Detailed Explanation

Topic description
In an orchard, Duoduo has knocked down all the fruits, and divided them into different piles according to different types of fruits. Duoduo decided to combine all the fruits into one pile.
For each merger, Duoduo can merge two piles of fruits together, and the energy consumed is equal to the sum of the weights of the two piles of fruits. It can be seen that all the fruits go through n − 1 n-1nAfter 1 merge, there is only one pile left. The total stamina consumed by Duoduo when merging fruits is equal to the sum of the stamina consumed for each merger.
Because it takes a lot of effort to move these fruits home, Duoduo should save as much energy as possible when merging the fruits. Assuming that the weight of each fruit is 1, and the number of types of fruits and the number of each fruit are known, your task is to design a combined sequence plan that minimizes the energy consumption of Duoduo, and outputs this minimum energy consumption value.
For example, there are 3 kinds of fruits, the numbers are 1, 2, 9 in turn. You can merge 1 and 2 piles first, the number of new piles is 3, and the energy consumption is 3. Then, merge the new pile with the original third pile to get a new pile with a number of 12 and a physical effort of 12. So Duoduo consumes a total of physical strength = 3 + 12 = 15. It can be proved that 15 is the minimum physical exertion value.
insert image description here

Input and output format
Input format:
The input file fruit.in includes two lines, the first line is an integer n (1 <= n <= 10000), indicating the number of types of fruit. The second line contains n integers, separated by spaces, the i-th integer ai (1 <= ai <= 20000) is the number of the i-th fruit.

Output format:
The output file fruit.out includes one line, which only contains an integer, which is the minimum physical exertion value. The input data guarantees that this value is less than 231.

Input and output samples
Input sample #1:
3
1 2 9
Output sample #1:
15
Prompt information
For 30% of the data, it is guaranteed that n <= 1000;
for 50% of the data, it is guaranteed that n <= 5000;
for All data are guaranteed to have n <= 10000.

The idea is very simple, it is a sort + greedy

#include <iostream>
#include <queue>
using namespace std;
priority_queue <int,vector<int>,greater<int> >a;
int n,s,x,y;
int main()
{
    
    
	cin >>n;
	for (int i=1;i<=n;i++)
	{
    
    
		cin >>x;
		a.push(x);
	}
	while (a.size()>=2)
	{
    
    
		x=a.top(); a.pop();
		y=a.top(); a.pop();
		s+=x+y;
		a.push(x+y);
	}
	cout <<s;
	return 0;
}

Guess you like

Origin blog.csdn.net/DUXS11/article/details/132122141