CSU->1588: 合併果子

1588: 合併果子

             Time Limit: 1 Sec     Memory Limit: 128 Mb     

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程序設計競賽初賽

題目鏈接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1588

題解:這道題看了別人的博客,瞭解到可以用優先隊列、哈夫曼樹、排序+貪心來解。但我個人還是用的優先隊列(優先隊列),畢竟這是最簡單容易想到的。

AC代碼

#include<iostream>
#include<queue>
using namespace std;

int main(){
    int T;
    scanf("%d",&T);
    int n;
    int tmp;
    priority_queue<int,vector<int>,greater<int> >q;
    while(T--){
        scanf("%d",&n);
        while(n--){
            scanf("%d",&tmp);
            q.push(tmp);
        }
        int x=0,y=0,sum=0;
        while(!q.empty()){
            x=q.top();
            q.pop();
            if(q.empty()){
                break;
            }
            y=q.top();
            q.pop();
            sum+=(x+y);
            q.push(x+y);
        }
        printf("%d\n",sum);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章