/* Floyd算法 */ /************************************************************************ Floyd算法的核心可用以下代码表示 for (int k = 0; k < n; ++k){ for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ if (d[i][j] < INF && d[k][j] < INF){ d[i][j] = min(d[i][j], d[i][k] + d[k][j]); }//if }//for(j) }//for(i) }//for(k) 时间复杂度: O(n^3) ************************************************************************/ #include <cstdio> int n, m; const int maxn = 100; const int INF = 65535; int w[maxn][maxn]; int d[maxn][maxn]; int p[maxn][maxn]; void Floyd(){ for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ d[i][j] = w[i][j]; p[i][j] = j; }//for(j) }//for(i) for (int k = 0; k < n; ++k){ for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ if (d[i][j] > d[i][k] + d[k][j]){ d[i][j] = d[i][k] + d[k][j]; p[i][j] = p[i][k]; } }//for(j) }//for(i) }//for(k) } int main() { int from, to, v; scanf("%d%d", &n, &m); //初始化权值 for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ w[i][j] = INF; } } for (int i = 0; i < n; ++i){ w[i][i] = 0; } //边的输入 for (int i = 0; i < m; ++i){ scanf("%d%d%d", &from, &to, &v); w[from][to] = w[to][from] = v; } Floyd(); for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ printf("%3d", d[i][j]); } printf(" "); } return 0; }