旧代码 - 最短路 Floyd

/*
PROG:   floyd
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, M, destination;
int edge[maxn][maxn], dist[maxn][maxn], path[maxn][maxn];

void Floyd()
{
    int i, j, k;
    for (i=0; i<N; ++i)
    {
        for (j=0; j<N; ++j)
        {
            dist[i][j] = edge[i][j];
            if (i!=j && dist[i][j]<INF)
                path[i][j] = i;
            else
                path[i][j] = -1;
        }    
    }// Init
    
    for (k=0; k<N; ++k)
    {
        for (i=0; i<N; ++i)
        {
            for (j=0; j<N; ++j)
            {
                if (k==i || k==j)   continue;
                if (dist[i][k]+dist[k][j]<dist[i][j])
                {
                    dist[i][j] = dist[i][k]+dist[k][j];
                    path[i][j] = path[k][j];
                }    
            }
        }
    }// Main_Process
}// Floyd

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

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

    int i, j, k, a, b, c;
    while (~scanf("%d %d", &N, &M), N+M!=0)
    {
        for (i=0; i<N; ++i)
        {
            for (j=0; j<N; ++j)
                edge[i][j] = INF;
        }// Init
        
        for (i=0; i<M; ++i)
        {
            scanf("%d %d %d", &a, &b, &c);
            edge[a][b] = c;
        }// Input
        
        Floyd();
        for (i=0; i<N; ++i)
        {
            for (j=0; j<N; ++j)
            {
                if (i != j)
                {
                    printf("%d->%d    %2d    ", i, j, dist[i][j]);
                    destination = j;
                    dfs(i, path[i][j], j);
                    printf("%d\n", j);
                }    
            }
        }// display the path
    }// end of while 
    
    return 0;
}
/*
Test:
    
4 8
0 1 1
0 3 4
1 2 9
1 3 2
2 0 3
2 1 5
2 3 8
3 2 6

0 0

Result:

0->1     1    0-->1
0->2     9    0-->1-->1-->3-->3-->2
0->3     3    0-->1-->1-->3
1->0    11    1-->3-->3-->2-->2-->0
1->2     8    1-->3-->3-->2
1->3     2    1-->3
2->0     3    2-->0
2->1     4    2-->0-->0-->1
2->3     6    2-->0-->0-->1-->1-->3
3->0     9    3-->2-->2-->0
3->1    10    3-->2-->2-->0-->0-->1
3->2     6    3-->2
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值