填坑行动14-差分约束
板子题
题目传送门
题目大意:给出 \(m\) 个不等式,其中有 \(n\) 个未知数。
\(
\left\{
\begin{array}{**lr**}
x_{a_1}-x_{b_1}\le y_1\\
x_{a_2}-x_{b_2}\le y_2\\
x_{a_3}-x_{b_3}\le y_3\\
\vdots \\
x_{a_m}-x_{b_m}\le y_m\\
\end{array}
\right.
\)
如果有解,则输出一组解,无解输出 NO
。
题目解析
我们可以用建模的方法来解决这个问题。
我们设每个 \(x_i\) 的解为第 \(i\) 个点的点权。
\(x_{a_1}-x_{b_1}\le y_1\) 就相当于节点 \(a_1,b_1\) 两点的点权之差小于等于 \(y_1\) ,我们可以建一条边,从 \(b_1\) 到 \(a_1\) ,边权为 \(y_1\)
这样就变成的一张图,我们发现我们只要跑一边最长路就可以了,同事我们还要判一下是否会有正环,如果有正环的话,那么就会变成 \(x_i-x_i>0\) 显然是无解的。
那么我们就只要跑一次SPFA就好了。
但是我们如果遇到其他不等式该怎么办呢?
\(a-b\le c\to a-b\le c\)
\(a-b<c \to a-b\le c-1(a,b,c\in \operatorname{Z})\)
\(a-b\ge c\to b-a\le-c\)
\(a-b>c \to b-a\le 1-c (a,b,c\in \operatorname{Z})\)
\(a=b \to a-b\le 0 \, b-a \le 0\)
代码
链式前向星存图+SPFA
#include<queue>
#include<cstdio>
#include<cstring>
#define maxn 5039
#define maxm 20039
using namespace std;
//#define debug
typedef int Type;
inline Type read(){
Type sum=0;
int flag=0;
char c=getchar();
while((c<'0'||c>'9')&&c!='-') c=getchar();
if(c=='-') c=getchar(),flag=1;
while('0'<=c&&c<='9'){
sum=(sum<<1)+(sum<<3)+(c^48);
c=getchar();
}
if(flag) return -sum;
return sum;
}
int n,m,u,v,w;
int head[maxn],nex[maxm],to[maxm],c[maxm],kkk;
#define add(x,y,z) to[++kkk]=y;\
nex[kkk]=head[x];\
head[x]=kkk;\
c[kkk]=z;
int dis[maxn],cnt[maxn],vis[maxn];
queue<int> q;
int check(){
memset(cnt,0,sizeof(cnt));
memset(vis,0,sizeof(vis));
memset(dis,0x7f,sizeof(dis));
dis[0]=0; q.push(0); vis[0]=1;
while(!q.empty()){
int cur=q.front(); q.pop(); vis[cur]=0;
for(int i=head[cur];i;i=nex[i])
if(dis[to[i]]>dis[cur]+c[i]){
dis[to[i]]=dis[cur]+c[i];
if(!vis[to[i]]){
vis[to[i]]=1;
cnt[to[i]]++;
q.push(to[i]);
if(cnt[to[i]]>n) return 1;
}
}
}
return 0;
}
int main(){
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
n=read(); m=read();
for(int i=1;i<=n;i++){
add(0,i,0);
}
for(int i=1;i<=m;i++){
u=read(); v=read(); w=read();
add(v,u,w);
}
if(check()){
printf("NO");
return 0;
}
for(int i=1;i<=n;i++) printf("%d ",dis[i]);
return 0;
}