1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| const int MAXN = 450; struct Edge { int to, weight; }; struct Node { int dis, from; bool operator>(const Node &a) const { return dis > a.dis; } }; vector<Edge> edges[MAXN]; vector<int> dis(MAXN), vis(MAXN); priority_queue<Node, vector<Node>, greater<Node>> que; void dijkstra(int n, int s) { dis = vector<int>(MAXN, INT_MAX); vis = vector<int>(MAXN, 0); dis[s] = 0; que.push({0, s}); while (!que.empty()) { int from = que.top().from; que.pop(); if (vis[from]) continue; vis[from] = 1; for (auto edge : edges[from]) { int to = edge.to, weight = edge.weight; if (dis[to] > dis[from] + weight) { dis[to] = dis[from] + weight; que.push({dis[to], to}); } } } }
void solve() { int n, m; cin >> n >> m; vector<array<int, 3>> bridges; for (int i = 1; i <= m; i++) { int u, v, w; cin >> u >> v >> w; bridges.push_back({u, v, w}); edges[u].push_back({v, w}); edges[v].push_back({u, w}); } vector<vector<int>> res_dis(n + 1); for (int i = 1; i <= n; i++) { dijkstra(n, i); res_dis[i] = dis; } int q; cin >> q; while (q--) { int k; cin >> k; vector<int> vec(k); for (auto &v : vec) cin >> v; sort(all(vec)); int ans = INT_MAX; auto dfs = [&](auto dfs, int cur, int i, int sum) { if (i == k) { ans = min(ans, sum + res_dis[cur][n]); return; } auto [u, v, w] = bridges[vec[i] - 1]; dfs(dfs, v, i + 1, sum + res_dis[cur][u] + w); dfs(dfs, u, i + 1, sum + res_dis[cur][v] + w); }; do { dfs(dfs, 1, 0, 0); } while (next_permutation(all(vec))); cout << ans << endl; } }
|