CSU-1588 合併果子

1588: 合併果子

         Time Limit: 1 Sec     Memory Limit: 128 Mb     Submitted: 1351     Solved: 580    

Description

現在有n堆果子,第i堆有ai個果子。現在要把這些果子合併成一堆,每次合併的代價是兩堆果子的總果子數。求合併所有果子的最小代價。

Input

第一行包含一個整數T(T<=50),表示數據組數。
每組數據第一行包含一個整數n(2<=n<=1000),表示果子的堆數。
第二行包含n個正整數ai(ai<=100),表示每堆果子的果子數。

Output

每組數據僅一行,表示最小合併代價。

Sample Input

2
4
1 2 3 4
5
3 5 2 1 4

Sample Output

19
33

Hint

Source

國防科學技術大學第十八屆銀河之光文化節ACM程序設計競賽初賽
思路:和POJ-3253幾乎一樣,每次尋找最少的兩堆進行合併即可。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
priority_queue <int,vector<int>,greater<int> > q;
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        int ans=0;
        cin >> n;
        int x;
        while(!q.empty())   q.pop();
        for(int i=0;i<n;i++)
        {
            cin >> x;
            q.push(x);
        }
        while(!q.empty())
        {
            int a=q.top();
            q.pop();
            int b=q.top();
            q.pop();
            ans=ans+a+b;
            q.push(a+b);
            if(q.size()==1)
                break;
        }
        cout << ans << endl;
    }
    return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章