我记得以前写过差分约数的博客,可是找不到了,就再写一遍吧。

a - b <= k -----> a <= b + k ------>要求最终结果满足这个式子,加源点跑最短路,若能跑出来,则最终一定满足。

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#define ll long long
#define llu unsigned ll
using namespace std;
const int maxn=11000;
int head[maxn],ver[maxn],edge[maxn],nt[maxn];
int dis[maxn],sum[maxn],tot=1,n,m;
bool ha[maxn];

void add(int x,int y,int z)
{
    ver[++tot]=y,edge[tot]=z;
    nt[tot]=head[x],head[x]=tot;
}

bool spfa(int s)
{
    memset(ha,0,sizeof(ha));
    memset(sum,0,sizeof(sum));
    memset(dis,0x3f,sizeof(dis));
    queue<int>q;
    q.push(s);
    dis[s]=0,ha[s]=true,sum[s]++;
    while(q.size())
    {
        int x=q.front();
        q.pop();
        ha[x]=false;
        for(int i=head[x];i;i=nt[i])
        {
            int y=ver[i],z=edge[i];
            if(dis[y]>dis[x]+z)
            {
                dis[y]=dis[x]+z;
                if(!ha[y])
                {
                    q.push(y);
                    ha[y]=true;
                    sum[y]++;
                    //加了一个源点
                    if(sum[y]>=n+1) return false;
                }
            }
        }
    }
    return true;
}

int main(void)
{
    int x,y,z;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&x,&y,&z);
        add(y,x,z);
    }
    for(int i=1;i<=n;i++)
        add(n+1,i,0);
    if(!spfa(n+1)) printf("NO\n");
    else
    {
        for(int i=1;i<=n;i++)
            printf("%d ",dis[i]);
    }
    return 0;
}