利用Bellman-Ford算法(有向图) 判断负环

时间:2023-03-10 06:59:25
利用Bellman-Ford算法(有向图) 判断负环
 // 根据Bellman-Ford算法的原理
// 判断负环(算法的最大更新次数,应该是顶点数-1次)
// 而如果存在负环,算法会一直更新下去 // 我们根据循环进行的次数,来判断负环 #include <iostream>
#include <cstdio>
#include <cstring> using namespace std; const int max_N=+;
const int max_E=+; int N,E; struct edge
{
int from,to,cost;
};
edge es[max_E]; int d[max_N]; void solve()
{
memset(d,,sizeof(d));
int cnt=;
while(cnt<N)
{
bool update=false;
for(int i=;i<E;++i)
{
edge e=es[i];
if(d[e.to]>d[e.from]+e.cost)
{
printf("hei ");
d[e.to]=d[e.from]+e.cost;
update=true;
}
}
if(update==false)
{
printf("NO\n");
break;
}
else
{
++cnt;
if(cnt==N)
{
printf("YES\n");
break;
}
}
}
} int main()
{
scanf("%d %d",&N,&E);
for(int i=;i<E;++i)
{
scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost);
}
solve();
return ;
} /*
7 10
0 1 2
0 2 5
1 2 4
1 3 6
1 4 10
2 3 2
3 5 1
4 5 3
4 6 5
5 6 9
NO
*/ /*
3 3
0 1 1
1 2 2
2 1 -2
NO
*/ /*
3 3
0 1 1
1 2 2
2 1 -3 */