當(dāng)前位置:
首頁 >
合并果子优先队列
發(fā)布時間:2025/4/5
32
豆豆
合并果子
每次取出兩個最小的,求和之后再放進(jìn)去,再取出兩個最小的,依次進(jìn)行下去。當(dāng)然,每次取出之后都需要累加兩個數(shù)。
本文使用優(yōu)先隊列,也就是最小堆實現(xiàn)
typedef long long ll; priority_queue< ll,vector<ll>,greater<ll> > pq;//從小到大排序優(yōu)先隊列的大小大于1pq.size()>1時,取出兩個top元素。
ac代碼
#include<iostream> #include<queue> using namespace std; const int maxn=1e4+10; typedef long long ll; ll n,sum=0,tmp;priority_queue<ll,vector<ll>,greater<ll> > pq;//從小到大 int main(){cin>>n;for(int i=0;i<n;i++){cin>>tmp;pq.push(tmp);}while(pq.size()>1){ll tmp1=pq.top();//最小的pq.pop();ll tmp2=pq.top();pq.pop();sum+=tmp1+tmp2;pq.push(tmp1+tmp2);}cout<<sum<<endl;return 0; }總結(jié)