旧代码 - 最短路 Spfa(邻接表)
来源:互联网 发布:南山软件产业基地 编辑:程序博客网 时间:2024/06/07 02:37
/*PROG: spfa_adjacent tableID : ouyangyeweiLANG: C++*/#include <queue>#include <cstdio>#include <cstdlib>using namespace std;#define onlinejudgeconst int maxn = 1004;const int INF = 0x3F3F3F3F;bool inq[maxn];int N, M, destination, dist[maxn], path[maxn];struct ArcNode{ int v, w; ArcNode *next;}*List[maxn];void spfa(int src){ int i, u; ArcNode *temp; queue <int> q; for (i=0; i<N; ++i) path[i]=-1, dist[i]=INF, inq[i]=false; dist[src]=0, inq[src]=true; q.push(src); while (!q.empty()) { u = q.front(); q.pop(); inq[u] = false; temp = List[u]; while (temp != NULL) { if (dist[u]+temp->w < dist[temp->v]) { path[temp->v] = u; dist[temp->v] = dist[u]+temp->w; if (!inq[temp->v]) q.push(temp->v), inq[temp->v]=true; } temp = temp->next; }// end of while }// end of while}// spfavoid 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, a, b, c; while (~scanf("%d %d", &N, &M), N+M!=0) { memset(List, 0, sizeof(List)); ArcNode *temp; for (i=0; i<M; ++i) { scanf("%d %d %d", &a, &b, &c); temp = new ArcNode; temp->v=b, temp->w=c, temp->next=NULL; if (List[a] == NULL) List[a] = temp; else temp->next=List[a], List[a]=temp; }// creat the adjacent table spfa( 0 ); for (i=1; i<N; ++i) { printf("%d ", dist[i]); destination = i; dfs(0, destination); printf("%d\n", i); }// end of for }// 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 */