1 solutions
-
0
C++ :
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; const int LOG = 18; // 2^17 = 131072,够用 vector<int> G[MAXN]; int depth[MAXN]; int up[MAXN][LOG]; void dfs(int u, int fa) { depth[u] = depth[fa] + 1; up[u][0] = fa; for (int k = 1; k < LOG; k++) { up[u][k] = up[ up[u][k-1] ][k-1]; } for (int v : G[u]) { if (v != fa) dfs(v, u); } } int lca(int a, int b) { if (depth[a] < depth[b]) swap(a, b); int diff = depth[a] - depth[b]; for (int k = 0; k < LOG; k++) { if ((diff >> k) & 1) a = up[a][k]; } if (a == b) return a; for (int k = LOG - 1; k >= 0; k--) { if (up[a][k] != up[b][k]) { a = up[a][k]; b = up[b][k]; } } return up[a][0]; } int dist(int a, int b) { int c = lca(a, b); return depth[a] + depth[b] - 2 * depth[c]; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; for (int i = 1; i < n; i++) { int x, y; cin >> x >> y; G[x].push_back(y); G[y].push_back(x); } dfs(1, 0); int Q; cin >> Q; while (Q--) { int x, y; cin >> x >> y; cout << dist(x, y) << '\n'; } return 0; }
- 1
Information
- ID
- 398
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- 10
- Tags
- # Submissions
- 4
- Accepted
- 3
- Uploaded By