#include #include #include #include using namespace std;

const int INF = INT_MAX;

void floyd(vector<vector>& graph, vector<vector>& path) { int n = graph.size(); for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (graph[i][k] != INF && graph[k][j] != INF && graph[i][k] + graph[k][j] < graph[i][j]) { graph[i][j] = graph[i][k] + graph[k][j]; path[i][j] = path[i][k]; } } } } }

void printPath(vector<vector>& path, int start, int end) { vector p; int cur = start; while (cur != end) { p.push_back(cur); cur = path[cur][end]; } p.push_back(end); for (int i = 0; i < p.size(); i++) { cout << p[i] << " "; } cout << endl; }

int main() { int s1, t1, s2, t2; cin >> s1 >> t1 >> s2 >> t2; int n, m; cin >> n >> m; vector<vector> graph(n, vector(n, INF)); vector<vector> path(n, vector(n, -1)); for (int i = 0; i < n; i++) { graph[i][i] = 0; } for (int i = 0; i < m; i++) { int a, b, c; cin >> a >> b >> c; graph[a - 1][b - 1] = c; graph[b - 1][a - 1] = c; path[a - 1][b - 1] = b - 1; path[b - 1][a - 1] = a - 1; } floyd(graph, path); if (graph[s1 - 1][t1 - 1] == INF) { cout << -1 << endl; } else { cout << graph[s1 - 1][t1 - 1] << endl; printPath(path, s1 - 1, t1 - 1); } if (graph[s2 - 1][t2 - 1] == INF) { cout << -1 << endl; } else { cout << graph[s2 - 1][t2 - 1] << endl; printPath(path, s2 - 1, t2 - 1); } return 0;

时间限制:1s 空间限制:512M 题目描述:用费洛伊德Floyd算法求任意两点最短路径。分别输出给定两对结点最短路径值并依次列出其路径结点。 输入格式:第一行二个整数 s1t1;第二行二个整数 s2t2;第三行二个整数 nm;n≤200 m≤40000随后 m 行每行三个整数 abc表示 a b 之间有一条权值为 c 的边。c≤109 输出格式:s1 到 t1 的最短路并输出路径按字典序输

原文地址: http://www.cveoy.top/t/topic/hDeS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录