spfa模板

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=10005,M=5e5+5;
int head[N],ver[M],edge[M],Next[M],d[N];
const int INF=0x7fffffff;
queue<int>q;
bool v[N];
int n,m,s,tot;
void add(int x,int y,int z)
{
    ver[++tot]=y,edge[tot]=z,Next[tot]=head[x],head[x]=tot;
}
void spfa()
{
    fill(d,d+n+1,INF);
    memset(v,0,sizeof(v));
    d[s]=0;v[s]=1;
    q.push(s);
    while(q.size())
    {
        int x=q.front();
        q.pop();
        v[x]=0;
        for(int i=head[x];i;i=Next[i])
        {
            int y=ver[i],z=edge[i];
            if(d[y]>d[x]+z)
            {
                d[y]=d[x]+z;
                if(!v[y])
                {
                    q.push(y);
                    v[y]=1;
                }
            }
        }
    }
}
int main()
{
    
    cin>>n>>m>>s;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        add(x,y,z);    
    }
    spfa();
    for(int i=1;i<=n;i++)
    {
        printf("%d ",d[i]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/hh13579/p/11385464.html