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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值