Easy sssp(spfa判负环与求最短路)

#include<bits/stdc++.h>
using namespace std;
int n,m,s;
struct node{
    int to,next,w;
}e[900000];
bool pc;
int dis[10000000],head[100000],vis[100000];
inline void read(int &x)
{
    x=0;int f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}
int num=0; 
void add(int x,int y,double c)
{
    e[++num].to=y;
    e[num].w=c;
    e[num].next=head[x];
    head[x]=num;
}
int cal[100000];
void spfa(int u,int h)
{    
    if(pc) return;
    vis[u]=h;
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].to;
        if(dis[v]>dis[u]+e[i].w)
        {
            dis[v]=dis[u]+e[i].w;
//            cout<<v<<' '<<dis[v]<<endl;system("pause");
            if(!vis[v]) spfa(v,h);
            if(pc) return;
            else if(vis[v]==h)
            {
                pc=true;return;
            }
        }
    }
    vis[u]=0; 
}
queue<int>q;
int path[100000];
void spfa2(int st)
{
    memset(vis,0,sizeof vis);
    memset(path,0x3f3f3f3f,sizeof path);
    vis[st]=1;
    path[st]=0;
    q.push(st);
    while(!q.empty())
    {
        int u=q.front();q.pop();vis[u]=0;
        for(int i=head[u];i!=-1;i=e[i].next)
        {
            int v=e[i].to;
            if(path[v]>path[u]+e[i].w)
            {
                path[v]=path[u]+e[i].w;
                if(!vis[v])
                {
                    q.push(v);
                    vis[v]=1;
                }
            }
        }
    }
}
int main()
{
    memset(head,-1,sizeof head);
    scanf("%d%d%d",&n,&m,&s);
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        read(x),read(y),read(z);
        add(x,y,z);
    }
    pc=0;
    memset(dis,0x3f,sizeof dis);
    memset(vis,0,sizeof vis);
    for(int i=1;i<=n;i++)
    {
        spfa(i,i);
        if(pc){
            puts("-1");
            return 0;
        }
    }
    spfa2(s);
    for(int i=1;i<=n;i++)
    {
        if(path[i]==0x3f3f3f3f){
            printf("NoPath
");
        }
        else{
            printf("%d
",path[i]);
        }
    }
    
}
原文地址:https://www.cnblogs.com/719666a/p/9568048.html