版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
- 题目大意:给定三个关系: 问是否存在一组解
- 思路:差分模板,因这题没有特殊要求,所以可以统一化大于等于跑最长路或小于等于跑最短路
- 注意事项:spfa要用dfs版判环,效率较高。要建立超源连接所有点,排除非连通图情况。
- 代码实现:
#include<bits/stdc++.h>
using namespace std;
struct node{
int to,nxt,val;
}e[30005];
int n,m,head[10005],tot;
void build(int a,int b,int c)
{
e[++tot].to=b;
e[tot].nxt=head[a];
e[tot].val=c;
head[a]=tot;
}
int dis[10005];
bool vis[10005];
void spfa(int p)
{
vis[p]=true;
for(int i=head[p];i;i=e[i].nxt)
{
if(dis[e[i].to]>dis[p]+e[i].val)
{
dis[e[i].to]=dis[p]+e[i].val;
if(vis[e[i].to])
{
printf("No");
exit(0);
}
spfa(e[i].to);
}
}
vis[p]=false;
}
int main()
{
scanf("%d%d",&n,&m);
for(int op,a,b,c,i=1;i<=m;i++)
{
scanf("%d",&op);
if(op==3)
{
scanf("%d%d",&a,&b);
build(a,b,0);
build(b,a,0);
}
else
{
scanf("%d%d%d",&a,&b,&c);
if(op==2)
{
build(b,a,c);
}
else
build(a,b,-c);
}
}
memset(dis,0x3f,sizeof(dis));
dis[0]=0;
for(int i=1;i<=n;i++)
build(0,i,1);
spfa(0);
printf("Yes");
return 0;
}