刚看这道题题面时并没有觉得这是道图论题。后来仔细想了想发现spfa可以做(遇图不决spfa)在输入的时候加几个判定就完事了。
上代码
#include<cstdio> #include<algorithm> #include<cmath> #include<cstring> #include<iostream> using namespace std; const int maxn = 50005; int n, m; inline int read() { int a=0; char x=getchar(); while(x<'0'||x>'9')x=getchar(); while(x>='0'&&x<='9')a=(a<<3)+(a<<1)+x-48,x=getchar(); return a; } struct edge { int to, nxt, w; } e[maxn]; int dis[maxn], cnt, tot[maxn], dep[maxn]; bool vis[maxn]; inline void add(int u, int v, int W) { e[++cnt].to = v; e[cnt].nxt = dep[u]; dep[u] = cnt; e[cnt].w = W; } inline bool spfa(int u) { vis[u] = 1; for(int i = dep[u]; i; i = e[i].nxt) if(dis[e[i].to] < dis[u] + e[i].w) { dis[e[i].to] = dis[u] + e[i].w; if(vis[e[i].to]) return 0; if(!spfa(e[i].to)) return 0; } vis[u]= 0; return 1; } int num, a, b, c; int main() { n = read(); m = read(); while(m--) { num = read(); a = read(); b = read(); if(num == 1) { c = read(); add(b,a,c); } else if(num == 2) { c = read(); add(a,b,-c); } else if(num == 3) { add(a,b,0); add(b,a,0); } } for(int i = 1; i <= n; i++) { add(0,i,0); dis[i] = -23333333; } if(!spfa(0)) printf("No"); else printf("Yes"); return 0; }