题目链接。
分析:
请参考本文章。
AC代码(输出的顺序不唯一):
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXN 102 #define min(x, y) ((x)<(y)?(x):(y)) const int INF = (1<<24); int G[MAXN][MAXN], dis[MAXN][MAXN], pre[MAXN][MAXN], path[MAXN]; int n, m, min_cost, cnt; void floyd(){ int i, j, k, p; for(i=0; i<n; i++){ for(j=0; j<n; j++){ dis[i][j] = G[i][j]; } dis[i][i] = 0; } for(k=0; k<n; k++){ for(i=0; i<k; i++){ for(j=i+1; j<k; j++){ if(min_cost > dis[i][j]+G[i][k]+G[k][j]){ min_cost = dis[i][j]+G[i][k]+G[k][j]; cnt = 0; p = j; while(p != i){ path[cnt++] = p; p = pre[i][p]; } path[cnt++] = i; path[cnt++] = k; } } } for(i=0; i<n; i++){ for(j=0; j<n; j++){ if(dis[i][j] > dis[i][k]+dis[k][j]){ dis[i][j] = dis[i][k]+dis[k][j]; pre[i][j] = pre[k][j]; } } } } } int main(){ int i, u, v, w, j; while(scanf("%d %d", &n, &m) == 2){ min_cost = INF; for(i=0; i<n; i++){ for(j=0; j<n; j++){ G[i][j] = INF; pre[i][j] = i; } } for(i=0; i<m; i++){ scanf("%d %d %d", &u, &v, &w); u--; v--; if(G[u][u]>w){ G[u][v] = G[v][u] = w; } } floyd(); if(min_cost == INF) printf("No solution.\n"); else{ for(i=0; i<cnt; i++){ if(i != cnt-1) printf("%d ", path[i]+1); else printf("%d\n", path[i]+1); } } } return 0; }