/*
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
*/
旧代码 - 最短路 Floyd
最新推荐文章于 2021-05-24 07:24:28 发布