CSU 1588【合并果子】

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 <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
using namespace std;
const int maxn=1005;
int a[maxn],b[maxn];
struct cmp{/定义比较结构
    bool operator ()(int &a,int &b){
        return a>b;//最小值优先
    }
};
struct cmp1{
    bool operator()(int &a,int &b){
        return a<b;//最大值优先,同默认优先
    }
};
priority_queue<int,vector<int>,cmp> pq;
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--){
        int sum=0,x;
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            pq.push(x);//入队列
        }
        while(!pq.empty()){
            int tmp=0,i;
            for(i=0;i<2;i++){//合并前两个元素
                if(pq.empty())
                    break;
                tmp+=pq.top();//tmp存放前两个元素的结果
                pq.pop();
            }
            if(i==2){//如果i!=2说明当前队列已经为空,不能在合并
                pq.push(tmp);
                sum+=tmp;
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37867156/article/details/80501986