差分约束
对于
\(a+b>=c\)
若干个这样的不等式
要求判断有无解
可以从最短路中得到启发
\(d[s]+w_{s->v}<=d[v]\)
从\(s\)到\(v\)连一条权值为\(w_{s->v}\)的边
从\(c\)到\(a\)连一条权值为\(-b\)的边
然后 用\(dfs\)优化\(spfa\)
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define reg register int
#define isdigit(x) ('0' <= x&&x <= '9')
template<typename T>
inline T Read(T Type)
{
T x = 0,f = 1;
char a = getchar();
while(!isdigit(a)) {if(a == '-') f = -1;a = getchar();}
while(isdigit(a)) {x = (x << 1) + (x << 3) + (a ^ '0');a = getchar();}
return x * f;
}
const int MAXN = 10010,MAXM = 20010,inf = 0x3f3f3f;
struct EDGE
{
int v,w,_nxt;
}edge[MAXM << 1];
int cnt,_ori[MAXN];
inline void add(int u,int v,int w)
{
edge[++cnt].v = v;
edge[cnt]._nxt = _ori[u];
edge[cnt].w = w;
_ori[u] = cnt;
}
#define code_out {printf("No");exit(0);}
typedef long long ll;
bool vis[MAXN];
ll d[MAXN];
int n,k;
bool able;
inline void _SPFA(int s)
{
vis[s] = 1;
for(reg e = _ori[s],v;e;e = edge[e]._nxt)
{
if(d[s] + edge[e].w > d[v = edge[e].v])
{
d[v] = d[s] + edge[e].w;
if(vis[v]) {able = 1;return;}
_SPFA(v);
if(able) return;
}
}
vis[s] = 0;
return;
}
int main()
{
n = Read(1),k = Read(1);
for(reg i = 1;i <= k;i++)
{
int sit = Read(1),u = Read(1),v = Read(1),w;
switch(sit)
{
case 1:
w = Read(1);
if(v == u&&!w) code_out
add(v,u,w);
break;
case 2:
w = Read(1);
if(v == u&&!w) code_out
add(u,v,-w);
break;
case 3:
add(u,v,0),add(v,u,0);
break;
}
}
for(reg i = 1;i <= n;i++) add(0,i,0),d[i] = -inf;
_SPFA(0);
if(!able) printf("Yes");
else printf("No");
return 0;
}