|
| 1 | +```cpp |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +#include <vector> |
| 5 | +#include <algorithm> |
| 6 | +#include <numeric> |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +int N, M, Q; |
| 10 | +int r[200001]{}, dep[200001]{}; |
| 11 | +int D[200001][18]{}, X[200001][18]{}; |
| 12 | +vector<vector<pair<int, int>>> V(200001); |
| 13 | + |
| 14 | +int f(int x) { return x == r[x] ? x : r[x] = f(r[x]); } |
| 15 | + |
| 16 | +void dfs(int n, int p, int d) { |
| 17 | + D[n][0] = p, dep[n] = d; |
| 18 | + for (auto[i, c] : V[n]) if (i != p) dfs(i, n, d + 1), X[i][0] = c; |
| 19 | +} |
| 20 | + |
| 21 | +void make() { |
| 22 | + for (int k = 1; k < 18; k++) for (int i = 1; i <= N; i++) { |
| 23 | + D[i][k] = D[D[i][k - 1]][k - 1]; |
| 24 | + X[i][k] = min(X[i][k - 1], X[D[i][k - 1]][k - 1]); |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +int solve(int a, int b) { |
| 29 | + if (dep[a] < dep[b]) swap(a, b); |
| 30 | + int diff = dep[a] - dep[b], res = 2e9; |
| 31 | + for (int i = 0; i < 18; i++) if (diff & (1 << i)) { |
| 32 | + res = min(res, X[a][i]); |
| 33 | + a = D[a][i]; |
| 34 | + } |
| 35 | + if (a == b) return res; |
| 36 | + while (D[a][0] != D[b][0]) { |
| 37 | + for (int i = 0; i < 18; i++) if (D[a][i] == D[b][i]) { |
| 38 | + i--; |
| 39 | + res = min({ res, X[a][i], X[b][i] }); |
| 40 | + a = D[a][i], b = D[b][i]; |
| 41 | + break; |
| 42 | + } |
| 43 | + } |
| 44 | + return min({ res, X[a][0], X[b][0] }); |
| 45 | +} |
| 46 | + |
| 47 | +int main() |
| 48 | +{ |
| 49 | + cin.tie(0)->sync_with_stdio(0); |
| 50 | + |
| 51 | + cin >> N >> M >> Q; |
| 52 | + vector<tuple<int, int, int>> E(M); |
| 53 | + for (auto &[v, x, y] : E) cin >> x >> y >> v; |
| 54 | + sort(E.begin(), E.end(), greater<>()); |
| 55 | + |
| 56 | + iota(r, r + N + 1, 0); |
| 57 | + for (auto[v, a, b] : E) { |
| 58 | + int x = f(a), y = f(b); |
| 59 | + if (x == y) continue; |
| 60 | + r[x] = y; |
| 61 | + V[a].emplace_back(b, v); |
| 62 | + V[b].emplace_back(a, v); |
| 63 | + } |
| 64 | + |
| 65 | + dfs(1, 0, 0); |
| 66 | + make(); |
| 67 | + |
| 68 | + for (int a, b; Q--;) { |
| 69 | + cin >> a >> b; |
| 70 | + cout << solve(a, b) << '\n'; |
| 71 | + } |
| 72 | + |
| 73 | +} |
| 74 | + |
| 75 | +``` |
0 commit comments