luogu P1993 小K的农场

luogu P1993 小K的农场_第1张图片

analysis

就是判断一组不等式是否有解

于是建立差分约束系统,有三个不等式(因为这个题没有要求作物个数的正负,我们完全可以使其为负):

c a s e 1 : a i − b i > = c i case1:a_i-b_i>=c_i case1:aibi>=ci

c a s e 2 : a i − b i < = c i case2:a_i-b_i<=c_i case2:aibi<=ci

c a s e 3 : { a i − b i > = 0 a i − b i < = 0 case3:\begin{cases} a_i-b_i>=0\\ a_i-b_i<=0 \end{cases} case3:{aibi>=0aibi<=0

code

#include
using namespace std;
#define loop(i,start,end) for(register int i=start;i<=end;++i)
#define clean(arry,num) memset(arry,num,sizeof(arry))
template<typename T>void read(T &x){
	x=0;T neg=1;char r=getchar();
	while(r>'9'||r<'0'){if(r=='-')neg=-1;r=getchar();}
	while(r>='0'&&r<='9'){x=(x<<1)+(x<<3)+r-'0';r=getchar();}
	x*=neg;
}
const int maxn=10000+10;
const int maxm=10000+10;
int n,m;
struct node{
	int e;
	int w;
	int nxt;
}edge[maxn<<1];
int head[maxn];
int cnt=0;
inline void addl(int u,int v,int w){
	edge[cnt].e=v;
	edge[cnt].w=w;
	edge[cnt].nxt=head[u];
	head[u]=cnt++;
}
bool vis[maxn];
int dis[maxn];
bool flag;
void spfa(int u){
	if(flag)
		return;
	vis[u]=true;
	for(int i=head[u];i!=-1;i=edge[i].nxt){
		int v=edge[i].e;
		if(dis[v]>dis[u]+edge[i].w){
			if(vis[v]){
				flag=true;
				return;
			}
			dis[v]=dis[u]+edge[i].w;
			spfa(v);
		}
	}
	vis[u]=false;
}
int main(){
	#ifndef ONLINE_JUDGE
    freopen("datain.txt","r",stdin);
    #endif
    read(n);
    read(m);
    clean(head,-1);
    loop(i,1,m){
    	int op,ai,bi,ci;
    	read(op);
		read(ai);
    	read(bi);
    	if(op!=3)
			read(ci);
		else ci=0; 
    	if(op==1)
    		addl(ai,bi,-ci);
    	else if(op==2)
    		addl(bi,ai,ci);
		else if(op==3){
    		addl(ai,bi,ci);
    		addl(bi,ai,ci);
		}
	}
	clean(dis,0x3f);
	dis[0]=0;
	loop(i,1,n)
		addl(0,i,0);
	clean(vis,false);
	flag=false;
	spfa(0);
	if(!flag)
		printf("Yes\n");
	else printf("No\n");
	return 0;
}

你可能感兴趣的:(图论算法)