合并果子优先队列
合并果子
每次取出兩個最小的,求和之后再放進去,再取出兩個最小的,依次進行下去。當然,每次取出之后都需要累加兩個數。
本文使用優先隊列,也就是最小堆實現
typedef long long ll; priority_queue< ll,vector<ll>,greater<ll> > pq;//從小到大排序優先隊列的大小大于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; }總結
- 上一篇: 优先队列重载
- 下一篇: c++98不支持set初始化列表