(Greedy, priority queues) were combined fruit

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45697774/article/details/102725127

(Chicken dish wrong title) Luo Gu wrong title record
code I copied someone else's! Invasion delete (* / ω\ *)
Here Insert Picture Description
We have STL! ! !
STL in the priority queue: priority_queue
definition:

priority_queue<int>q;

From small to large:

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

If you want to descending, then you can overload operators:

struct Node{
    int x,y;
    Node(int a=0, int b=0):
        x(a), y(b) {}
};
struct cmp{
    bool operator()(Node a, Node b){
        if(a.x == b.x)  return a.y>b.y;
        return a.x>b.x;
    }
};
priority_queue<Node,vector<Node>,cmp>q;

Or you can use les
descending s)

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

This last question is the Word of the water:

#include<bits/stdc++.h>
using namespace std;
int n,x,ans;
priority_queue<int,vector<int>,greater<int> >q;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) cin>>x,q.push(x);
    while(q.size()>=2){
        int a=q.top(); q.pop();
        int b=q.top(); q.pop();
        ans+=a+b;
        q.push(a+b);
    }
    cout<<ans<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45697774/article/details/102725127
Recommended