今天上午刚讲了差分约束,这个是练习题。
就是个比较明显【luo】的差分约束+SPFA判负环
注意spfa判负环的过程和怎么建边就可以了
我是神奇的传送门
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int tot;
int n,m;
const int maxn=100000+15;
int head[maxn],next[maxn<<1],d[maxn];
bool used[maxn];
struct haha
{
int f,t,cost;
}es[maxn<<1];
void init()
{
memset(head,-1,sizeof(head));
tot=0;
}
void build(int ff,int tt,int dd)
{
es[++tot]=(haha){ff,tt,dd};
next[tot]=head[ff];
head[ff]=tot;
}
queue<int>q;
bool flag;
int tim[maxn];
bool done[maxn];
void spfa(int s)
{
memset(d,0x3f,sizeof(d));
d[s]=0;
q.push(s);
used[s]=1;
tim[s] = 0;
done[s] = true;
while(!q.empty())
{
int u=q.front();
q.pop();
used[u]=0;
done[u] = true;
for(int i=head[u];i != -1;i=next[i])
{
int v=es[i].t;
if(d[v]>d[u]+es[i].cost)
{
d[v]=d[u]+es[i].cost;
if(!used[v])
{
q.push(v);
used[v]=1;
}
tim[v] = tim[u] + 1;
if(tim[v] > n + 1)
{
flag=1;
return;
}
}
}
}
}
int main()
{
int a,b,c;
int t;
scanf("%d%d",&n,&m);
init();
for(int i=1;i<=m;i++)
{
scanf("%d",&t);
if(t==1)
{
scanf("%d%d%d",&a,&b,&c);
build(a,b,-c);
}
else if(t==2)
{
scanf("%d%d%d",&a,&b,&c);
build(b,a,c);
}
else if(t==3)
{
scanf("%d%d",&a,&b);
build(b,a,0);
build(a,b,0);
}
}
for(int i=1;i<=n;i++)
{
if(!done[i])
spfa(i);
if(flag)
{
puts("No");
return 0;
}
}
puts("Yes");
return 0;
}