Merged Fruit (Classic Priority Queue)

Merged Fruit (Classic Priority Queue)

https://www.luogu.com.cn/problem/P1090

Title 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.

Every time you merge, Toto can merge two piles of fruits together, and the energy consumed is equal to the sum of the weight 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 for each merge.

Because it takes great 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 fruit types and the number of each fruit are known, your task is to design a combined sequence plan to minimize the amount of physical effort that Duoduo consumes, and output the minimum physical effort value.

For example, there are 3 kinds of fruits, the numbers are 1, 2, 9 in order. You can merge 1 and 2 piles first, the number of new piles is 3, and the physical effort is 3. Then, merge the new pile with the original third pile, and get a new pile with a number of 12 and a physical effort of 12. So Dato consumes a total of physical strength=3+12=15. It can be proved that 15 is the minimum physical cost.

Input format

There are two lines.
The first line is an integer n (1≤n≤10000), indicating the number of fruit types.

The second line contains n integers, separated by spaces, the i-th integer ai a_iaiIs the number of the i-th fruit.

Output format

An integer, which is the minimum physical cost. Input data to ensure that this value is less than 2 32 2^{32}232

Sample input and output

Enter #1

3 
1 2 9 

Output #1

15

Instructions/tips

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, it is guaranteed that n≤10000.

answer

Similar to the optimal binary tree, the smallest and smallest are continuously merged.

At this time, it is very convenient to use the priority queue. Every time the head of the queue is the smallest, the second is the second smallest.

Take out the first two numbers every time, add them and stuff them into the queue

Then until a pile is formed.

#include<bits/stdc++.h>
using namespace std;
priority_queue<int,vector<int>,greater<int> >q;//小顶堆,升序队列 
int main()
{
	int n,temp1,temp2,t=0;
	cin>>n;
	int a[n+5];
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
		q.push(a[i]);
	}
	int k=1;
	while(k<n)
	{
		temp1=q.top();
		q.pop();
		temp2=q.top();
		q.pop();
		q.push(temp1+temp2);
		t=t+temp1+temp2;
		k++;
	}
	cout<<t<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/hhuhgfhggy/article/details/109277123