Line 1: 1 integer N (2 <= N <= 50000) Lines 2 - N + 1: 1 integer Li per line (1 <= Li <= 1000).
Output with minimal physical exertion.
3 3 4 5
19
I think it's easier to understand this question backwards. I will give you some sticks to connect them. You can only connect two sticks at a time (the stamina spent is the total length of the two sticks). The solution to changing the meaning of the question must be to connect the two shortest wooden sticks each time. After the connection is completed, put the connected wooden stick as a wooden stick and put it into all the wooden sticks, and then find the shortest two wooden sticks to connect, only After the last stick is left, getting the least amount of physical effort is the result we want.
Example: Three sticks: 3 4 5
First connection: 5, 7 Stamina cost: 7
Second connection: 12 Stamina cost: 12
Total cost 19;
The priority queue (priority_queue) is used in the following reference code
priority_queue< int > q; // int ascending priority queue
priority_queue <int, vector<int>, greater<int> > // int descending priority queue
If you want to know more about the priority queue, you can go to the information.
#include <iostream> #include <vector> #include <queue> using namespace std; intmain() { priority_queue <int, vector<int>, greater<int> > Q; // Build a descending priority queue, that is, the head of the queue is the minimum value in the queue int n; cin >> n; int temp; for(int i=1; i<=n; i++) { cin >> temp; Q.push( temp ); } // enter the queue long long ans = 0; int time = 0; while( !Q.empty() ){ have = 0; has += Q.top(); Q.pop(); has += Q.top(); Q.pop(); // Continue to connect the smallest two sticks until the last one is left ans += has; if(Q.empty()) { break; } Q.push( tem ); } cout << ans << endl; return 0; }