旧代码 - 最短路 Bellman Ford

/*
PROG:   Bellman_Ford
ID  :   ouyangyewei
LANG:   C++
*/
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define onlinejudge

const int maxn = 1004;
const int INF = 0x3F3F3F3F;

int N, destination, dist[maxn], path[maxn], edge[maxn][maxn];

void Bellman_Ford(int src)
{
    int i, j, k, u, v;
    for (i=0; i<N; ++i)
    {
        dist[i] = edge[src][i];
        if (i!=src && dist[i]<INF)
            path[i] = src;
        else
            path[i] = -1;
    }// k=1 : dist( 1 )[u]
    
    for (k=2; k<N; ++k)
    {
        for (u=0; u<N; ++u)
        {
            if (u != src)
            {
                for (j=0; j<N; ++j)
                {
                    if (edge[j][u]<INF && dist[u]>dist[j]+edge[j][u])
                        path[u]=j, dist[u]=dist[j]+edge[j][u];
                }
            }
        }// u
    }// k : dist( k )[u]
}// Bellman_Ford

void dfs(int src, int xx)
{
    if (xx != src)
        dfs(src, path[xx]);
    
    if (xx != destination)
        printf("%d-->", xx);
    
    return ;
}// dfs

int main()
{
#ifdef onlinejudge
    freopen("E:\\bellman.txt", "r", stdin);
    freopen("E:\\bellman_ans.txt", "w", stdout);
#endif

    int u, v, w, i, j;
    while (~scanf("%d", &N), N!=0)
    {
        while (~scanf("%d %d %d", &u, &v, &w), u+v+w!=-3)
        {
            edge[u][v] = w;
        }// Input
        
        for (i=0; i<N; ++i)
        {
            for (j=0; j<N; ++j)
            {
                if (i == j)
                    edge[i][j] = 0;
                else if (edge[i][j] == 0)
                    edge[i][j] = INF;
            }
        }// preprocess
        
        Bellman_Ford( 0 );
        
        for (i=1; i<N; ++i)
        {
            printf("The lowcosts is: %d\n", dist[i]);
            
            destination = i;
            dfs( 0, i );
            printf("%d\n", i);
        }    
    }// End of While
    
    return 0;
}
/*
Test:
    
7 10
0 1 6
0 2 5
0 3 5
1 4 -1
2 1 -2
2 4 1
3 2 -2
3 5 -1
4 6 3
5 6 3

0 0

Result:
  
1     0-->3-->2-->1
3     0-->3-->2
5     0-->3
0     0-->3-->2-->1-->4
4     0-->3-->5
3     0-->3-->2-->1-->4-->6  
*/

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