Floyd 最小环模板题
code
/* floyd最小环,记录路径,时间复杂度O(n^3) 不能处理负环 */ #include <iostream> #include <cstring> using namespace std; const int INF = 109, maxn = 252645135; int g[INF][INF], dis[INF][INF], pre[INF][INF]; int ans[INF]; //pr[i][j]记录i到j最短路径的第一个点 int n, m, tem , tol; int main() { while (cin >> n >> m) { tem = maxn; memset (g, 0xf, sizeof g); memset (dis, 0xf, sizeof dis); memset (pre, 0, sizeof pre); int x, y, z; for (int i = 1; i <= m; i++) { cin >> x >> y >> z; if (z < g[x][y]) dis[x][y] = dis[y][x] = g[x][y] = g[y][x] = z; pre[x][y] = y, pre[y][x] = x; } for (int k = 1; k <= n; k++) { for (int i = 1; i < k; i++) for (int j = i + 1; j < k; j++) { if (tem > dis[i][j] + g[i][k] + g[k][j]) { tem = dis[i][j] + g[i][k] + g[k][j]; int t = i; tol = 0; while (t != 0) { ans[++tol] = t; t = pre[t][j]; } ans[++tol] = k; } } for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (i != j && dis[i][k] + dis[k][j] < dis[i][j]) { dis[i][j] = dis[i][k] + dis[k][j]; pre[i][j] = pre[i][k]; } } if (tem == maxn) cout << "No solution."; else for (int i = 1; i <= tol; i++) cout << ans[i] << ‘ ‘; cout << endl; } return 0; }
时间: 2024-10-13 23:06:48