luogu P1993 小K的农场(差分约束)

找到了一个写差分约束很详细的博客,包括了各种关系的转换,传送门:https://blog.csdn.net/chenxiaoran666/article/details/82083724

题面传送:https://www.luogu.org/problemnew/show/P1993

这就是道很典型的差分约束题啦

操作一,我们有x-y>=z,即y-x<=-c,从y向x连一条值为-z的边

操作二,我们有x-y<=z,从x向y连一条值为z的边

操作三,我们有x=y,从x向y连一条值为0的边,从y向x连一条值为1的边

然后我们发现,如果条件矛盾则有负环产生,然后就转换成spfa判负环的问题啦,注意我们构造出来的图不一定是一个连通图,所以要把每个图都跑一边...

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <queue>
#define maxn 10010
using namespace std;

bool vis[maxn],sear[maxn];
int n,m,opt,x,y,z,num;
int fir[maxn],dis[maxn],cnt[maxn];
queue<int> q;

struct qwq
{
	int to,nxt,val;
}e[maxn<<1];

int read()
{
	int xx=0,kk=1;char ch=' ';
	while(!isdigit(ch)){ch=getchar();if(ch=='-')kk=-1;}
	while(isdigit(ch)){xx=xx*10+ch-'0';ch=getchar();}
	return kk*xx;
}

void addedge(int u,int v,int w)
{
	e[++num].to=v;
	e[num].val=w;
	e[num].nxt=fir[u];
	fir[u]=num;
}

bool spfa(int s)
{
	memset(dis,127,sizeof(dis));
	dis[s]=0;q.push(s);vis[s]=true;
	while(!q.empty())
	{
		int sx=q.front();q.pop();sear[sx]=true;
		for(int i=fir[sx];i;i=e[i].nxt)
		{
			int tx=e[i].to;
			if(dis[tx]>dis[sx]+e[i].val)
			{
				dis[tx]=dis[sx]+e[i].val;
				cnt[tx]=cnt[sx]+1;
				if(cnt[tx]>=n) return false;
				if(!vis[tx])
				    q.push(tx),vis[tx]=true;
			}
		}
		vis[sx]=false;
	}
	return true;
}

int main()
{
	n=read();m=read();
	while(m--)
	{
		opt=read();x=read();y=read();
		switch(opt)
		{
			case 1:{z=read();addedge(y,x,-z);break;}
			case 2:{z=read();addedge(x,y,z);break;}
			case 3:{addedge(x,y,0);addedge(y,x,0);break;}
		}
	}
	for(int i=1;i<=n;++i)
	{
		if(sear[i]) continue;
		if(!spfa(i)){puts("No");return 0;}
	}
	puts("Yes");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40942982/article/details/82387165