差分约束。
发现题中每个农场的作物数
x
i
x_i
xi 要满足以下约束关系:
{
x
a
−
x
b
≥
c
1
x
a
−
x
b
≤
c
2
x
a
=
x
b
{xa−xb≥c1xa−xb≤c2xa=xb
把以上关系进行转化,重点是“相等”这一约束关系的转化:
{
x
a
−
x
b
≥
c
1
x
b
−
x
a
≥
−
c
2
x
b
−
x
a
≥
0
x
a
−
x
b
≥
0
{xa−xb≥c1xb−xa≥−c2xb−xa≥0xa−xb≥0
按照上述约束关系,SPFA 求最长路即可。注意此时 dis 要赋值为
−
inf
-\inf
−inf。
注意若图不连通,可能会出现有 x i x_i xi 值为 − inf -\inf −inf 的情况,所以要建立超级源点。
#include
using namespace std;
const int maxn=5005,maxm=1e4+5;
int head[maxn],cnt,tot[maxn],dis[maxn],n,m;
bool vis[maxn];
struct edge{int to,nxt,w;}e[maxm];
void add(int x,int y,int z){e[++cnt]={y,head[x],z},head[x]=cnt;}
bool spfa(int s)
{
queue<int> q;
memset(dis,-0x3f3f3f,sizeof dis);
dis[s]=0,q.push(s),vis[s]=1,tot[s]++;
while(!q.empty())
{
int x=q.front();q.pop(),vis[x]=0;
for(int i=head[x];i;i=e[i].nxt)
if(dis[e[i].to]<dis[x]+e[i].w)
{
dis[e[i].to]=dis[x]+e[i].w;
if(!vis[e[i].to]) vis[e[i].to]=1,q.push(e[i].to),tot[e[i].to]++;
if(tot[e[i].to]>=n) return 0;
}
}
return 1;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int op;cin>>op;
if(op==1)
{
int a,b,c;cin>>a>>b>>c;
add(b,a,c);
}
else if(op==2)
{
int a,b,c;cin>>a>>b>>c;
add(a,b,-c);
}
else
{
int a,b;cin>>a>>b;
add(a,b,0),add(b,a,0);
}
}
for(int i=1;i<=n;i++) add(0,i,0);
if(spfa(1)) cout<<"Yes";
else cout<<"No";
return 0;
}