优先队列

img

从大到小:

priority_queue<int,vector<int>,less<int>>p; p r i o r i t y _ q u e u e < i n t , v e c t o r < i n t > , l e s s < i n t >> p ;

从小到大:

priority_queue<int,vector<int>,greater<int>>q; p r i o r i t y _ q u e u e < i n t , v e c t o r < i n t > , g r e a t e r < i n t >> q ;

优先队列里放 pair p a i r :

typede t y p e d e pair<LL,int>PII; p a i r < L L , i n t > P I I ;
vector<PII>ans; v e c t o r < P I I > a n s ;
priority_queue<PII,vector<PII>,greater<PII>>que; p r i o r i t y _ q u e u e < P I I , v e c t o r < P I I > , g r e a t e r < P I I >> q u e ;

这里是首先让第一元素从小到大排序,当第一元素相等时,再按第二元素从大到小排序。

优先队列自定义重载:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef long long LL;

const int maxn = 1e5 + 5;

struct X{
    int a,b;
    X () {}
    X (int aa,int bb) {
        a = aa,b = bb;
    }
    friend bool operator < (const X A, const X B){
        if(A.a == B.a) return A.b > B.b; //这里是反过来的,小于就是大于,大于就是小于。
        else return A.a > B.a;
    }
};

X ans[maxn];
priority_queue <X> pq;

int main(){
    ans[1].a = 1;
    ans[1].b = 2;
    ans[2].a = 2;
    ans[2].b = 1;
    ans[3].a = 1;
    ans[3].b = 3;
    pq.push(ans[1]);
    pq.push(ans[3]);
    pq.push(ans[2]);
    while(!pq.empty()){
        X k = pq.top();
        pq.pop();
        printf("%d %d\n",k.a,k.b);
    }
}

输出:
1 2
1 3
2 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值