旧代码 - 最短路 Bellman Ford(邻接表)
来源:互联网 发布:c语言鸡兔同笼循环 编辑:程序博客网 时间:2024/06/08 16:36
/*PROG: Bellman FordID : ouyangyeweiLANG: C++*/#include <stdio.h>#include <stdlib.h>#include <memory.h>#define onlinejudgeconst 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_Fordvoid dfs(int src, int xx){ if (xx != src) dfs(src, path[xx]); if (xx != destination) printf("%d-->", xx); return ;}// dfsint 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 100 1 60 2 50 3 51 4 -12 1 -22 4 13 2 -23 5 -14 6 35 6 30 0Result: 1 0-->3-->2-->13 0-->3-->25 0-->30 0-->3-->2-->1-->44 0-->3-->53 0-->3-->2-->1-->4-->6 */