dij和spfa双合一

· · 题解

#include<bits/stdc++.h>
using namespace std;
const int maxn=1000001;
const int maxm=1000001;
const int maxx=0x3f3f3f3f;
inline int read()
{
    register int x=0;
    register int t=1;
    register char ch=getchar();
    while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    if(ch=='-') t=-1,ch=getchar();
    while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
    return x*t;
}
struct edge
{
    int v,d,next;
    edge(int v,int d,int next):v(v),d(d),next(next){}
    edge(){}
}que[maxm];
int head[maxn],edgenub=0;
struct heapnode
{
    int s,d;
    bool operator<(const heapnode &a)const{return d>a.d;}
    heapnode(int s,int d):s(s),d(d){}
    heapnode(){}
};
priority_queue<heapnode> di;
queue<int> sp;
bool flag[maxn];
int dis[maxn],n,m,s;
void dij()
{
    for(int i=1;i<=n;i++)
    dis[i]=maxx;
    dis[s]=0;
    di.push(heapnode(s,dis[s]));
    heapnode it;
    while(!di.empty())
    {
        it= di.top();
        int u=it.s;
        di.pop();
        if(dis[u]!=it.d) continue;
        int p=head[u];
        do//dowhile
        {
            int v=que[p].v,d=que[p].d;
            if(dis[v]>dis[u]+d)
            {
                dis[v]=dis[u]+d;
                di.push(heapnode(v,dis[v]));
            }
            p=que[p].next;
        }while(p!=0);
    }
}
void spfa()
{
    for(int i=1;i<=n;i++)
    dis[i]=maxx;
    dis[s]=0;
    sp.push(s);
    while(!sp.empty())
    {
        int u=sp.front();
        sp.pop();
        flag[u]=0;
        for(int i=head[u];i;i=que[i].next)//for
        {
            int v=que[i].v,d=que[i].d;
            if(dis[v]>dis[u]+d)
            {
                dis[v]=dis[u]+d;
                if(!flag[v])
                {
                    flag[v]=1;
                    sp.push(v);
                }
            }
        }
    }
}
void addedge(int u,int v,int d)
{
    que[++edgenub]=edge(v,d,0);
    que[edgenub].next=head[u];
    head[u]=edgenub;
}
int main()
{
    n=read();
    m=read();
    s=read();
    for(int i=0;i<m;i++)
    {
        int u=read(),
            v=read(),
            d=read();
        addedge(u,v,d);
    }
    //spfa();
    dij();
    for(int i=1;i<=n;i++)
    {   if(dis[i]==maxx) cout<<2147483647;
        else cout<<dis[i];
        cout<<" ";
    }
}