c++优先队列,小根堆

14 篇文章 0 订阅
4 篇文章 0 订阅

一直对priority不会,现在要记一下了

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

这样的话,我们可以得到一个小根堆;
意思大概是<类型,<存储方式>,<比较函数> >;
但是这个小根堆只能支持int;
反正我不会啦;

struct cs{
    int x;
    bool operator < (const cs &rhs) const {
        return x > rhs.x;
    }
}a;
priority_queue<cs>Q;

这个是一个结构体的小根堆;
开心;
我们可以再结构体里面放各种东西;
感谢wl大佬;

给一个测试的代码;

#include<bits/stdc++.h>
#define Ll long long
using namespace std;
struct cs{
    int x;
    bool operator < (const cs &rhs) const {
        return x > rhs.x;
    }
}a;
priority_queue<cs>Q;
priority_queue<int,vector<int>,greater<int> >q;

int x,y;
int main()
{
    while(1){
        cin>>x;
        if(x==1){
            scanf("%d",&y);
            a.x=y;
            Q.push(a);
        }
        if(x==2){
            cout<<Q.top().x<<endl;
            Q.pop();
        }
    }
}

关于重载运算符,好像还有一种更简单的写法

bool operator <(H x,H y){return x.v>y.v;}

那么dijkstra的最优化最短路
https://www.luogu.org/problem/show?pid=2934

#include<bits/stdc++.h>
#define Ll long long
using namespace std;
const int N=1e4+5;
struct H{int x,y;};
struct cs{int to,nxt,v;}a[500005];
int d[N],head[N],ll;
bool vi[N];
int n,m,x,y,z,S;
void init(int x,int y,int v){
    a[++ll].to=y;
    a[ll].v=v;
    a[ll].nxt=head[x];
    head[x]=ll;
}
H mH(int x,int y){H a;a.x=x;a.y=y;return a;}
bool operator <(H x,H y){return x.x>y.x;}
void dijkstra()
{
    for(int i=0;i<=n;i++)d[i]=2147483647;   
    priority_queue<H>Q;d[S]=0;Q.push(mH(0,S));
    while(!Q.empty()){
        H c=Q.top();Q.pop();
        if(vi[c.y])continue; 
        int x=c.y;vi[x]=1;
        for(int k=head[x];k;k=a[k].nxt)
            if(!vi[a[k].to]&&d[a[k].to]>d[x]+a[k].v)
                d[a[k].to]=d[x]+a[k].v,Q.push(mH(d[a[k].to],a[k].to));
    }
}
int main()
{
    scanf("%d%d%d",&n,&m,&S);
    for(int i=1;i<=m;i++)
        scanf("%d%d%d",&x,&y,&z),init(x,y,z);
    dijkstra();
    for(int i=1;i<=n;i++)printf("%d ",d[i]);
}

感觉数据还是比较优秀的

  • 12
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值