合并果子(multiset)

合并果子

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 312   Solved: 113
[ Submit][ Status][ Web Board]

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


代码:
#include<cstdio> 
#include<set> 
using namespace std; 
  
multiset<int> mst; 
  
int main() 
{ 
    int t; 
    scanf("%d",&t); 
    while(t--) 
    { 
        mst.clear(); 
        int n; 
        int ans=0; 
        scanf("%d",&n); 
        for(int i=1;i<=n;i++) 
        { 
            int x; 
            scanf("%d",&x); 
            mst.insert(x); 
        } 
        int anss; 
        multiset<int>::iterator it1; 
        multiset<int>::iterator it2; 
        while(mst.size()>1) 
        { 
            it1=it2=mst.begin(); 
            it2++; 
            anss=*it1+*it2; 
            ans=ans+anss; 
            mst.erase(mst.begin()); 
            mst.erase(mst.begin()); 
            mst.insert(anss); 
        } 
        printf("%d\n",ans); 
    } 
    return 0; 
} 



你可能感兴趣的:(set)