/** cpp **/#include<bits/stdc++.h>usingnamespace std;constint INF =99999;
vector<int> dis;boolBellmanFord(int n,vector<vector<int>>& G){int m = G.size();// 1.初始化源点到其他点的权值
dis = vector<int>(n +1,INF);
dis[1]=0;// 2.进行k - 1次松弛,每次松弛对所有的边进行优化for(int k =1;k <= n -1;++k){int check =0;// 进行判断可以提前退出松弛for(int i =0;i < m;++i){if(dis[G[i][1]]> dis[G[i][0]]+ G[i][2]){
dis[G[i][1]]= dis[G[i][0]]+ G[i][2];
check =1;}}if(check ==0)break;}// 3.判断是否存在负权环for(int i =0;i < m;++i){if(dis[G[i][1]]> dis[G[i][0]]+ G[i][2])returnfalse;}returntrue;}intmain(void){/**n:节点数,G:边的集合.**/
vector<vector<int>> G{{2,3,2},{1,2,-3},{1,5,5},{4,5,2},{3,4,3}};int n =5;// vector<vector<int>> G{{4,6,1},{1,2,20},{1,3,5},{4,1,-200},{2,4,4},{4,2,4},{3,4,2}};// int n = 6;// vector<vector<int>> G{{1,2,1},{1,3,3},{2,4,5},{3,4,1},{4,2,-3}};// int n = 4;bool res =BellmanFord(n,G);if(res ==false) cout <<"Gragh has negative cycle"<< endl;else{
cout <<"min distance from source point to other points"<< endl;for(int i =1;i <(int)dis.size();++i) cout << dis[i]<<" ";
cout << endl;}return0;}
java版
/** java **/publicclassBellmanFord{staticint[] dis =newint[1000];staticint INF =99999;publicstaticvoidmain(String[] args){int[][] G =newint[][]{{2,3,2},{1,2,-3},{1,5,5},{4,5,2},{3,4,3}};int n =5;boolean res =bellmanFord(n,G);if(res ==false) System.out.println("Gragh has negative cycle");else{
System.out.println("min distance from source point to other points");for(int i =1;i <= G.length;++i) System.out.print(dis[i]+" ");
System.out.println();}}publicstaticbooleanbellmanFord(int n,int[][] G){int m = G.length;for(int i =0;i < n +1;++i) dis[i]= INF;
dis[1]=0;for(int k =1;k <= n -1;++k){int check =0;for(int i =0;i < m;++i){if(dis[G[i][1]]> dis[G[i][0]]+ G[i][2]){
dis[G[i][1]]= dis[G[i][0]]+ G[i][2];
check =1;}}if(check ==0)break;}for(int i =0;i < m;++i){if(dis[G[i][1]]> dis[G[i][0]]+ G[i][2])returnfalse;}returntrue;}}