/*
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, M, destination;
int dist[maxn], path[maxn];
struct EDGE
{
int u, v, w;
}edge[maxn];
void Bellman_Ford( int src )
{
int i, k;
for (i=0; i<N; ++i)
{
dist[i]=INF, path[i]=-1;
}// preprocess
dist[src] = 0;
for (k=1; k<N; ++k)
{
for (i=0; i<M; ++i)
{
if (dist[edge[i].u]<INF
&& dist[edge[i].u]+edge[i].w<dist[edge[i].v])
{
dist[edge[i].v] = edge[i].w+dist[edge[i].u];
path[edge[i].v] = edge[i].u;
}
}// end of for
}// end of for
}// 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 i, j, a, b, c;
while (~scanf("%d", &N), N!=0)
{
M = 0;
while (~scanf("%d %d %d", &a, &b, &c), a+b+c!=-3)
{
edge[M].u=a, edge[M].v=b, edge[M].w=c;
++M;
}// input
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(邻接表)
原文作者:Bellman - ford算法
原文地址: https://blog.csdn.net/yeweiouyang/article/details/8636575
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
原文地址: https://blog.csdn.net/yeweiouyang/article/details/8636575
本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。