Merging fruits-remember the priority queue

priority_queue <int,vector<int>,less<int> > p;
priority_queue <int,vector<int>,greater<int> > q;

{5,4,1,2}
less:{5,4,2,1}
greater:{1,2,4,5}
Less is from big to small, and greater is from small to big.

#include<bits/stdc++.h>
using namespace std;
priority_queue <int,vector<int>,greater<int>>p;
int a;
int main(){
    
    
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
    
    
        scanf("%d",&a);
        p.push(a);
    }
    int x,y;
    int ans=0;
    while(p.size()!=1){
    
    
        x=p.top();
        p.pop();
        y=p.top();
        p.pop();
        ans+=x+y;
        p.push(x+y);
    }
    printf("%d",ans);
    return 0;
}

Guess you like

Origin blog.csdn.net/iuk11/article/details/109391942