#include<iostream>
#include<algorithm>
#include<limits>
#include<queue>
#include<stack>
#include<vector>
#include<math.h>
#include<string>
#include<stdio.h>
#include<string.h>
#include<cmath>
using namespace std;
/*
spfa 算法原理:
对bellman-ford 算法进行优化:
bellman-ford:
循环k次,就能找到从 1号点经过不超过k条边
走到每个点的最短距离
for n 次
for edge in edges edges{a,b,w}
dist[b]=min(dist[b],dist[a]+w)
优化: 不一定每次都要遍历全部边,因为可以观察到,dist[b]要想减小,一定是dist[a]减小了,
说明我们只要维护变小的点,就可以通过这些点对出边,来跟新后继节点,
spfa找负环思路:
我们单独维护一个cnt数组, cnt[x]代表到达x的最短路的边数
如果有n个节点,而
cnt[x] >=n 说明x的最短路边数最小为n,而路径的节点数最小为n+1 又因为
只有n个节点,所以一定存在负环
*/
struct ed
{
/* data */
int next,to,dis;
};
const int maxn=2005;
const int maxm=100004;
ed eds[maxm];
int head[maxn];
int cnt;
void add(int a,int b,int c)
{
//++cnt;
eds[cnt].to=b;
eds[cnt].dis=c;
eds[cnt].next=head[a];
head[a]=cnt++;
}
bool IsLoop;
bool IsInQue[maxn];
int distence[maxn];
int countEdge[maxn];
int n,m;
bool visited[maxn];
void spfa()
{
IsLoop=false;
memset(distence,0x3f,sizeof(distence));
//distence[1]=0;
//countEdge[1]=0;
for(int j=1;j<=n;j++)
{
IsInQue[j]=true;
queue<int>nodes;
nodes.push(j);
while(nodes.empty()==false)
{
int top=nodes.front(); nodes.pop();
IsInQue[top]=false;
// if(countEdge[top]>=n){
// IsLoop=true;
// return ;
// }
for(int i=head[top];i!=0;i=eds[i].next)
{
// cout<<top<<" "<<eds[i].to<<" "<<i<<endl;
int To=eds[i].to;
if(distence[To]>distence[top]+eds[i].dis)
{
if(IsInQue[To]==false)
{
IsInQue[To]=true;
nodes.push(To);
// countEdge[To]=countEdge[top]+1;
}
// countEdge[To]=max(countEdge[To],countEdge[top]+1);
distence[To]=distence[top]+eds[i].dis;
countEdge[To]=countEdge[top]+1;
if(countEdge[To]>=n){
IsLoop=true;
return ;
}
}
}
}
}
}
//例题 acwing 852
int main()
{
//freopen("out.txt","w",stdout);
cnt=1;
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
spfa();
if(IsLoop) printf("Yes\n");
else printf("No\n");
// for(int i=1;i<=n;i++)
// cout<<i<<" "<<distence[i]<<" "<<countEdge[i]<<endl;
return 0;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交