SPFA

来源:互联网 发布:淘宝整点秒杀网址 编辑:程序博客网 时间:2024/05/29 07:38
#include<cstdio>#include<queue>#include<cstring>using namespace std;queue<int>q;int F,N,M,W,dis[5001],a,b,w,pre[5001],z,flag,g[5001],fir[5001];struct node{    int t,wt,m;}st[500001];int main(){    flag=0;    memset(dis,127/3,sizeof dis);    memset(st,0,sizeof st);    memset(pre,0,sizeof pre);    scanf("%d%d",&N,&M);    for(int i=1;i<=M;i++){        scanf("%d%d%d",&a,&st[i].t,&st[i].wt);        st[i].m=fir[a],fir[a]=i;    }    q.push(1);    dis[1]=0;    pre[1]=1;    while(!q.empty()){        z=q.front();        for(int i=fir[z];i;i=st[i].m)            if(dis[st[i].t]>dis[z]+st[i].wt){                dis[st[i].t]=dis[z]+st[i].wt;                pre[st[i].t]=pre[z]+1;                if(pre[st[i].t]>N){printf("No Solution");return 0;}                if(g[st[i].t]) continue;                g[st[i].t]=1;                q.push(st[i].t);            }        g[q.front()]=0;        q.pop();    }    printf("%d",dis[N]);}
原创粉丝点击