hdu 懒省事的小明

很简单的一道优先队列问题,思路如下:

每次合并最小的两堆,并把新堆放入队列中,直到只剩下一堆为止

注意:

1 优先队列让最小的在队首要用greater<>,最大的要用less

2每次从优先队列取出两个值取两个值,因此当只剩下一个值的时候无法再取两个值了

代码如下:

#include<iostream>
#include<string>
#include<queue>
#include<algorithm>
#include<set>
using namespace std;
struct cmp{  
    bool operator ()(long long &a,long long &b){  
        return a>b;  
    }  
};  
int main(){
	int test;
	cin>>test;
	while(test--){
		int n;
		cin>>n;
		priority_queue<long long ,vector<long long>,cmp>q;
		for(int i=1;i<=n;i++){
			int temp;
			cin>>temp;
			q.push(temp);
		}
		long long ans=0;
		while(!q.empty()){
			int t1,t2;
			t1=q.top();
			q.pop();
			if(q.empty())break;
			t2=q.top();
			q.pop();
			ans+=t1+t2;
			q.push(t1+t2);
		//	cout<<ans<<" ";
		}
		cout<<ans<<endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值