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
| #include <cstdio> #include <algorithm> using namespace std; const int N = 5e5 + 10, M = 1e6 + 10, K = 20; int n, q, rt, d[N]; int idx, hd[N], nxt[M], edg[M]; int stmp, id[N], st[N << 1][K], lg[N << 1]; void dfs(int x, int fa) { st[++stmp][0] = x; d[x] = d[fa] + 1; id[x] = stmp; for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != fa) { dfs(edg[i], x); st[++stmp][0] = x; } } int dmin(int x, int y) { return d[x] < d[y] ? x : y; } void init() { for (int i = 2; i <= stmp; i++) lg[i] = lg[i >> 1] + 1; for (int k = 1; (1 << k) <= stmp; k++) for (int i = 1; i + (1 << k) - 1 <= stmp; i++) st[i][k] = dmin(st[i][k - 1], st[i + (1 << k - 1)][k - 1]); } int lca(int x, int y) { x = id[x], y = id[y]; if (x > y) swap(x, y); int k = lg[y - x + 1]; return dmin(st[x][k], st[y - (1 << k) + 1][k]); } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d%d%d", &n, &q, &rt); for (int i = 1; i <= n; i++) hd[i] = -1; for (int i = 1, a, b; i < n; i++) { scanf("%d%d", &a, &b); add(a, b); add(b, a); } dfs(rt, 0); init(); for (int x, y; q; q--) { scanf("%d%d", &x, &y); printf("%d\n", lca(x, y)); } return 0; }
|