#include <iostream>
using namespace std;
int n, m;
int u[100], v[100], w[100], dis[100];
const int INF = 0x3f3f3f3f;
int check = 0, flag = 0;
int main(){
cin>>n>>m;
for(int i=1; i<=m; i++){
cin>>u[i]>>v[i]>>w[i];
}
dis[1] = 0;
for(int i=2; i<=n; i++){
dis[i] = INF;
}
//提前终止
for(int k=1; k<=n-1; k++){
check = 0;
for(int i=1; i<=m; i++){
if(dis[v[i]] > dis[u[i]] + w[i]){
dis[v[i]] = dis[u[i]] + w[i];
check = 1;
}
}
if(check == 0){
break;
}
}
//检测负权回路
for(int i=1; i<=m; i++){
if(dis[v[i]] > dis[u[i]] + w[i]){
flag = 1;
}
}
if(flag == 1){
cout<<"存在负权回路。"<<endl;
}else {
for(int i=1; i<=n; i++){
cout<<dis[i]<<' ';
}
}
return 0;
}
Bellman-Ford 扩展
最新推荐文章于 2024-04-17 16:21:42 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)