toj-3488-stones2(优先队列)

Given n piles of stones, now we want to combine them into one pile. In order to finish this job, first we can select two piles arbitrarily, combine them into one; then select two piles from the remaining piles arbitrarily, combine them into one pile, and so on .. until there is only one pile. When we combine two piles, we need to cost some energy, and the cost is related to the sum of the number of stones in both pile. That is to say: If we combine two piles of the size 3 and 5, the energy cost is 8. Now our task is: given the size of the n piles, colculate how much energy we need to finish the job at least?

Input

The first line of the input is a single integer t, representing the number of test cases. The 2i-th and the 2i+1 -th lines describe the i-th test case. The 2i-th line gives the integer n, then the 2i+1 -th line gives n integers - the size of each pile. (0 < n ≤ 100000, and the size of each pile is no more than 100).

Output

For each test cases, output a single integer: the minmun energy we should cost.

Sample Input

1
4
5 9 6 3

Sample Output

45



方法一:优先队列,简单题

#include
#include
using namespace std;
struct cmp
{
    bool operator()(const int a, const int b) const
    {
        return a > b;
    }
};
int main()
{
    priority_queue,cmp>p;
    int T, num, n[100002];
    cin >> T;
    while(T--)
    {
        cin >> num;
        for(int i=0; i         {
            cin >> n[i];
            p.push(n[i]);
        }
        if(num == 1)
            cout << 0 << endl;
        else
        {
            int sum = 0;
            while(p.size()>=2)
            {
                int a = p.top();
                p.pop();
                int b = p.top();
                p.pop();
                sum += a+b;
                p.push(a+b);
            }
            cout << sum << endl;
        }
        while(!p.empty())
            p.pop();
    }
    return 0;
}


你可能感兴趣的:(toj-3488-stones2(优先队列))