Floyd-Warshall算法其实是比较容易理解也比较容易coding的DP... 不说了,上代码:
#include <cmath> #include <cstdio> #include <vector> #include <map> #include <set> #include <unordered_set> #include <string> #include <iostream> #include <algorithm> using namespace std; int main() { // Get input int n, m; cin >> n >> m; const int INVALID = std::numeric_limits<int>::max(); vector<vector<int>> mat(n, vector<int>(n, INVALID)); for (int i = 0; i < n; i++) mat[i][i] = 0; while (m--) { int i, j, len; cin >> i >> j >> len; mat[i - 1][j - 1] = std::min(mat[i - 1][j - 1], len); mat[j - 1][i - 1] = mat[i - 1][j - 1]; } // Floyd-Warshall for (int k = 0; k < n; k ++) for (int i = 0; i < n; i ++) for (int j = 0; j < n; j++) { if (i != j && i != k && j != k) { if (mat[i][k] != INVALID && mat[k][j] != INVALID) mat[i][j] = std::min(mat[i][j], mat[i][k] + mat[k][j]); } } // Output for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cout << mat[i][j] << " "; } cout << endl; } return 0; }