差分约束呢,就是给出一些形如x-y<=b不等式的约束,问是否满足有解的问题。
我们可能看不出来这种类型的题目到底有什么特点,但不可否认,这类问题可以转化为图论最短路问题。
例:bzoj2330 scoi2011 糖果
Description
幼儿园里有N个小朋友,lxhgww老师现在想要给这些小朋友们分配糖果,要求每个小朋友都要分到糖果。但是小朋友们也有嫉妒心,总是会提出一些要求,比如小明不希望小红分到的糖果比他的多,于是在分配糖果的时候,lxhgww需要满足小朋友们的K个要求。幼儿园的糖果总是有限的,lxhgww想知道他至少需要准备多少个糖果,才能使得每个小朋友都能够分到糖果,并且满足小朋友们所有的要求。
Input
输入的第一行是两个整数N,K。 接下来K行,表示这些点需要满足的关系,每行3个数字,X,A,B。 如果X=1,
表示第A个小朋友分到的糖果必须和第B个小朋友分到的糖果一样多; 如果X=2, 表示第A个小朋友分到的糖果必须少于第B个小朋友分到的糖果;
如果X=3, 表示第A个小朋友分到的糖果必须不少于第B个小朋友分到的糖果; 如果X=4,
表示第A个小朋友分到的糖果必须多于第B个小朋友分到的糖果; 如果X=5, 表示第A个小朋友分到的糖果必须不多于第B个小朋友分到的糖果;Output
输出一行,表示lxhgww老师至少需要准备的糖果数,如果不能满足小朋友们的所有要求,就输出-1。
Sample Input
5 7
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
Sample Output
11
Hint 【数据范围】
对于30%的数据,保证 N<=100 对于100%的数据,保证 N<=100000
对于所有的数据,保证 K<=100000,1<=X<=5,1<=A, B<=N
1,2,3,4,5分别对应A=B,A< B,A>=B,A>B,A<=B这五种情况.
so.. x=1时,AB两点的边权为0,可构建双向边;x=2时,A<=B+1,A to B的最小边权为1,构建单向边;x=3时,B to A的最小边权为0,构建单向边;x=4时,A>B,A>=B+1,B to A的最小边权为1,构建单向边;x=5时,A to B的最小边权为0,构建单向边。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 233333;
int n,k,x,a,b,h,tot;
int first[maxn],next[maxn<<1],d[maxn<<2],tim[maxn];
bool used[maxn],vis;
struct edge{
int from,to,cost;
}es[maxn<<1];
void build(int f,int t,int d)
{
es[++tot]=(edge){f,t,d};
next[tot]=first[f];
first[f]=tot;
}
void init()
{
memset(first,-1,sizeof(first));
tot=0;
}
deque<int>q;
bool spfa(int s)
{
d[s] = 0;
q.push_front(s);
used[s] = 1;
while(!q.empty())
{
int x = q.front();
q.pop_front();
used[x] = 0;
for(int i = first[x]; i != -1; i = next[i])
{
int u = es[i].to;
if(d[u] < d[x] + es[i].cost)
{
d[u] = d[x] + es[i].cost;
if(!used[u])
{
if(++ tim[u] > n)
return true;
used[u] = 1;
if(q.empty())
q.push_back(u);
else if(d[q.front()] < d[u])
q.push_front(u);
else
q.push_back(u);
}
}
}
}
return false;
}
int main()
{
long long ans=0;
scanf("%d%d",&n,&k);
init();
for(int i=1;i<=k;i++)
{
scanf("%d%d%d",&x,&a,&b);
if(x==1)
build(a,b,0),build(b,a,0);
else if(x==2)
build(a,b,1);
else if(x==3)
build(b,a,0);
else if(x==4)
build(b,a,1);
else if(x==5)
build(a,b,0);
}
for(int i=n;i>0;i--)
{
build(0,i,1);
}
if(spfa(0)==0)
{
for(int i=1;i<=n;i++)
{
ans+=d[i];
}
}
else ans=-1;
printf("%lld",ans);
return 0;
}