[luogu1993] 小K的农场
Solution
算是一道差分约束的模板题了。
将符号统一一下,如果是小于号就求负环,否则求正环
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 10005
struct edge{
int v,w,next;
}G[MAXN<<2];
int head[MAXN];
int vis[MAXN];
int dis[MAXN];
int N,M,tot = 0;
inline int read(){
int num = 0;char ch = getchar();
while(ch>'9'||ch<'0')ch = getchar();
while(ch>='0'&&ch<='9')num = num*10+ch-'0',ch = getchar();
return num;
}
inline void add(int u,int v,int w){
G[++tot].v = v;G[tot].w = w;G[tot].next = head[u];head[u] = tot;
}
bool dfs(int u){
vis[u] = 1;
for(register int i=head[u];i!=-1;i=G[i].next){
int v = G[i].v;
if(dis[v]>dis[u]+G[i].w){
dis[v] = dis[u] + G[i].w;
if(vis[v]||dfs(v))return true;
}
}
vis[u] = 0;
return false;
}
int main(){
N = read();M = read();
std::memset(head,-1,sizeof(head));
std::memset(vis,0,sizeof(vis));
int opt,u,v,w;
for(register int i=1;i<=M;++i){
opt = read();u = read();v = read();
if(opt==3){
add(u,v,0);add(v,u,0);
}
else{
w = read();
if(opt==1)add(u,v,-w);
else add(v,u,w);
}
}
for(register int i=1;i<=N;++i)add(0,i,0);
for(register int i=1;i<=N;++i)dis[i] = MAXN;
dis[0] = 0;
if(dfs(0))puts("No");
else puts("Yes");
return 0;
}