差分约束

#include<bits/stdc++.h>
using namespace std;
#define N 5005
int n,m,x,y,z,dis[N],u[N],k,h[N];
struct AB{
    int a,b,c,n;
}d[N*2];
void cun(int x,int y,int z){d[++k]=(AB){x,y,z,h[x]},h[x]=k;}
int spfa(int x){
    u[x]=1;
    for(int i=h[x];i;i=d[i].n){
        int y=d[i].b;
        if(dis[x]+d[i].c<dis[y]){
            dis[y]=dis[x]+d[i].c;
            if(u[y]||spfa(y)) return 1;
        }
    }
    u[x]=0;
    return 0;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        scanf("%d%d%d",&x,&y,&z);
        cun(y,x,z);
    } 
    for(int i=1;i<=n;i++) cun(0,i,0);
    memset(dis,9,sizeof(dis));
    dis[0]=0;
    if(spfa(0)) printf("NO\n");
    else{
        for(int i=1;i<=n;i++) printf("%d ",dis[i]);
    }
    return 0;
}
posted @ 2022-08-11 14:28  hubingshan  阅读(13)  评论(0)    收藏  举报  来源