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> #define re register const int MAXn = 5e5; const int MAXm = MAXn; const int MAXq = 5e5;
int head[MAXn + 10], cntnex, nex[MAXm * 2 + 10], to[MAXm * 2 + 10]; void Insert(int u, int v) { nex[++cntnex] = head[u]; head[u] = cntnex; to[cntnex] = v; }
int headq[MAXn + 10], cntnexq, nexq[MAXq + 10], q[MAXq + 10]; void Insertq(int u, int v) { nexq[++cntnexq] = headq[u]; headq[u] = cntnexq; q[cntnexq] = v; }
int fa[MAXn + 10]; bool vis[MAXn + 10]; void Dfs1(int cur) { vis[cur] = 1; for (re int i = head[cur]; i; i = nex[i]) { if (vis[to[i]]) continue; fa[to[i]] = cur; Dfs1(to[i]); } } int times[MAXn + 10], ans[MAXq + 10]; void Dfs2(int cur) { ++times[cur]; for (re int i = headq[cur]; i; i = nexq[i]) { int id = q[i]; while (times[id] != 1) { id = fa[id]; } ans[i] = id; } for (re int i = head[cur]; i; i = nex[i]) { if (times[to[i]]) continue; Dfs2(to[i]); } ++times[cur]; }
int n, Q, root, qid_nexq[MAXq + 10]; int main() { scanf("%d %d %d", &n, &Q, &root); for (re int i = 1, u, v; i < n; ++i) { scanf("%d %d", &u, &v); Insert(u, v); Insert(v, u); } Dfs1(root); for (re int i = 1, u, v; i <= Q; ++i) { scanf("%d %d", &u, &v); Insertq(u, v); qid_nexq[i] = cntnexq; } Dfs2(root); for (re int i = 1; i <= Q; ++i) { printf("%d\n", ans[qid_nexq[i]]); } }
|