差分约束

差分约束基本思想:给出一些不等式,最后询问这些不等式是否能够同时成立

首先要将不等式换成dis(a)-dis(b)<=k的形式,

然后建立从b到a长度为k的边,

最后利用spfa求一遍最短路,判断是否有负环,即可

如果有负环,则说明该不等式组不能同时成立

spfa模版:

const int MAXN=1010;
const int MAXM=20010;
int tot;
const long long INF=1e11;
int head[MAXN];
bool vis[MAXN];
int cnt[MAXN];
long long dist[MAXN];

struct Edge
{
    int to;
    int cost;
    int next;
}edge[MAXM];

void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}

void addedge(int u,int v,int w)
{
    edge[tot].to=v;
    edge[tot].cost=w;
    edge[tot].next=head[u];
    head[u]=tot++;
}

bool SPFA(int start,int n)
{
    memset(vis,false,sizeof(vis));
    for(int i=1;i<=n;i++)
    {
        dist[i]=INF;
    }
    vis[start]=true;
    dist[start]=0;
    queue<int>que;
    while(!que.empty())
        que.pop();
    que.push(start);
    memset(cnt,0,sizeof(cnt));
    cnt[start]=1;
    while(!que.empty())
    {
        int u=que.front();
        que.pop();
        vis[u]=false;
        for(int i=head[u];i!=-1;i=edge[i].next)
        {
            int v=edge[i].to;
            if(dist[v]>dist[u]+edge[i].cost)
            {
                dist[v]=dist[u]+edge[i].cost;
                if(!vis[v])
                {
                    vis[v]=true;
                    que.push(v);
                    if(++cnt[v]>n)
                        return false;
                }
            }
        }
    }
    return true;
}
原文地址:https://www.cnblogs.com/wsruning/p/5749290.html