Bellman_Ford算法求最短路径

/*bellman_ford算法*/
#include <iostream>
#include <fstream>
using namespace std;

#define SIZE 100
#define INL 1000000

int graph[SIZE][SIZE];
int n;
int t[SIZE];
int d[SIZE];
fstream fin;

bool bellman_ford(int s);
int main()
{
    fin.open("1004.txt",ios::in);
    int m;
    fin>>n>>m;
    int i,j;
    
    //邻接数据 
    for(i=0;i<n;i++)
      for(j=0;j<n;j++)
        graph[i][j]=INL;
    
    for(i=0;i<m;i++)
    {
        int x,y;
        fin>>x>>y;
        fin>>graph[x][y];
    }
    
   if(!bellman_ford(0))
      cout<<"can't find the best way!"<<endl;
    else
    {
        bellman_ford(0);
        for(int i=0;i<n;i++)
          cout<<d[i]<<" ";
        cout<<endl;
    }        
    system("pause");
    return 0;
} 

bool bellman_ford(int s)
{
    //初始化程序
     for(int i=0;i<n;i++)
     {
         d[i]=INL;
         t[i]=-1;
     }
     
     d[s]=0;
     
     for(int i=0;i<n-1;i++)
     {
         for(int j=0;j<n;j++)
           for(int k=0;k<n;k++)
           {
               if(graph[j][k]<INL)
               {
                   if(d[k]>d[j]+graph[j][k])
                     {
                         d[k]=d[j]+graph[j][k];
                         t[k]=j;
                     }    
               }
           }
     }
        
     for(int i=0;i<n;i++)
       for(int j=0;j<n;j++)
       {
           if(graph[i][j]<INL)
           {
               d[j]>d[i]+graph[i][j];
                return false;
           }
       }
     return true;       
}

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/Enigma_hao/article/details/8991828
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞