/*
PROG: spfa
ID : ouyangyewei
LANG: C++
*/
#include <queue>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define onlinejudge
const int maxn = 1004;
const int INF = 0x3F3F3F3F;
bool inq[maxn];
int N, M, destination;
int dist[maxn], path[maxn], edge[maxn][maxn];
void spfa(int src)
{
int i, u;
queue <int> q;
dist[src]=0, inq[src]=true;
q.push(src);
while (!q.empty())
{
u = q.front();
q.pop();
inq[u] = false;
for (i=0; i<N; ++i)
{
if (dist[u]+edge[u][i] < dist[i])
{
path[i] = u;
dist[i] = dist[u]+edge[u][i];
if (!inq[i])
q.push(i), inq[i]=true;
}
}// end of for
}// end of while
}// spfa
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 %d", &N, &M), N+M!=0)
{
memset(dist, INF, sizeof(dist));
memset(inq, false, sizeof(inq));
memset(edge, INF, sizeof(edge));
for (i=0; i<M; ++i)
{
scanf("%d %d %d", &a, &b, &c);
edge[a][b] = c;
}// end of for
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 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
*/
旧代码 - 最短路 Spfa
最新推荐文章于 2021-03-27 18:16:18 发布