差分约束的模版题,建图我们选择 a b c 代表 v(b) - v(a) <= -c 建图,然后注意到在区间 [ i , i + 1] 里面,有 v(i + 1) - v(i) <= 1
且 v(i) - v(i + 1) <= 0,这样建图,可以保证整张图的联通性,然后spfa跑图上最短路(有负权边),如果存在负环,则方程无解,否则若存在最短路,则必定有解,据说递归spfa跑负环特别快(逃。
代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> Pi;
typedef unsigned long long ULL;
int gcd(int a,int b){if (b == 0) return a; return gcd(b , a%b);}
int lcm(int a, int b){ return a/gcd(a,b)*b;}
inline int read(){
int f = 1, x = 0;char ch = getchar();
while (ch > '9' || ch < '0'){if (ch == '-')f = -f;ch = getchar();}
while (ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}
return x * f;
}
const int maxn = 1e5 + 10;
int n,m,tot;
int head[maxn],dis[maxn],vis[maxn],cnt[maxn];
int q[maxn*10],l,r;
struct _edge {
int to,nex,w;
}edge[maxn];
void add(int u,int v,int w){
edge[tot].to = v;
edge[tot].w = w;
edge[tot].nex = head[u];
head[u] = tot++;
}
int _spfa(int u){
vis[u] = 1;
for (int i=head[u]; ~i; i = edge[i].nex) {
int v = edge[i].to;
if (dis[v] > dis[u] + edge[i].w){
dis[v] = dis[u] + edge[i].w;
if (vis[v]) return 0;
if (!_spfa(v)) return 0;
}
}
vis[u] = 0;
return 1;
}
int main(){
// freopen("/Users/chutong/data.txt", "r", stdin);
n = read(); m = read();
memset(head, -1, sizeof(head));
for (int i=1; i<=m; i++) {
int tag = read();
if (tag == 1){
int a = read(),b = read(),c = read();
add(b, a, -c);
}else if (tag == 2){
int a = read(),b = read(),c = read();
add(a, b, c);
}else if (tag == 3){
int a = read(),b = read();
add(a, b, 0); add(b, a, 0);
}
}
for (int i=1; i<=n; i++)
add(0, i, 0);
for (int i=1; i<=n; i++)
dis[i] = INT_MAX;
if (!_spfa(0)) puts("No");
else puts("Yes");
return 0;
}