P1097Merge Fruit accepted Tags: greedy noip Group 2004<textarea id="code" class="textbox" style=""></textarea>Describe
In an orchard, Toto has beaten down all the fruits and divided them into different heaps according to the different kinds of fruit. A lot decided to synthesize all the fruits.
Each time a merger, a lot can combine the two fruits together, the energy consumed equals two of the weight of the sum of the fruit. It can be seen that all the fruit after the N-1 merger, there is only a pile. The total amount of energy consumed in the merging of fruits equals the physical strength of each merger.
Because it's going to take a lot of effort to bring the fruit home, you need to save as much as you can when you combine the fruit. Assuming that each fruit has a weight of 1, and that the number of fruits and the number of each fruit is known, your task is to design a combination of sequential schemes that will consume the least amount of energy and output this minimum physical cost.
For example, there are 3 kinds of fruit, the number is 1,2,9. The 1 and 2 stacks can be merged first, and the new heap number is 3, which consumes 3 of the energy. Next, the new heap is merged with the original third heap, and a new heap is obtained, with a number of 12, which consumes 12 of the energy. So the total cost of energy =3+12=15. It can be shown that 15 is the minimum physical cost.
Format input Format
The input consists of two lines, the first line being an integer n (1<=n<=10000), which represents the number of species of fruit. The second line contains n integers, separated by spaces, and the first integer AI (1<=ai<=20000) is the number of fruit of the first I.
Output format
The output includes one row, which contains only an integer, which is the minimum physical cost. The input data guarantees that this value is less than 2^31.
Example 1 sample input 1[copy]
3 1 2 9
Sample output 1[Copy]
Limit
1s per test point
Source
NOIp 2004
Thank you, Daniel, for sharing his exquisite algorithm!!
#include <iostream> #include <queue> #include <cstdio>using namespace std;priority_queue<int> Q; The priority queue for the C++stl library, where the elements from top to bottom are all from large to small int main () { int n,i,x,a=0,t; cin>>n; for (i=0;i<n;i++) { cin>>x; Q.push (-X); Plus the minus sign guarantees that the top two elements are the smallest of two integers } for (i=1;i<n;i++ ) { t=q.top (); T access is the smallest of the top two number of the and, that is, the physical value of each move a-=q.top (); A access is the total physical value of q.pop (); T+=q.top (); A-=q.top (); Q.pop (); Q.push (t); } cout<<a; return 0;}
vijos-p1097-Merging fruits (simple greedy && priority Queue && C + +)