题目传送门:https://www.luogu.com.cn/problem/P3379
倍增LCA模板:
1 #include<iostream>
2 #include<cstdio>
3 #include<algorithm>
4 #include<vector>
5 #include<map>
6 #include<queue>
7 #include<set>
8 #include<cmath>
9 #include<list>
10 #include<cstring>
11 #include<string>
12 #define ll long long
13 #define ull unsigned long long
14 #define inf 0x3f3f3f3f
15 #define inff 0x7fffffff
16 using namespace std;
17 const int N = 500000 + 10;
18
19 int fa[N][31], dep[N];
20 vector<int>G[N];
21
22 void dfs(int x, int pre) {
23
24 fa[x][0] = pre;
25 dep[x] = dep[pre] + 1;
26 for (int i = 1; i <= 30; i++) {
27 fa[x][i] = fa[fa[x][i - 1]][i - 1];
28 }
29 for (int i = 0; i < G[x].size(); i++) {
30 if (G[x][i] != pre) dfs(G[x][i], x);
31 }
32
33 }
34
35 int lca(int x, int y) {
36
37 if (dep[x] < dep[y]) swap(x, y);
38 for (int i = 30; i >= 0; i--) {
39 if ((1 << i) <= dep[x] - dep[y]) x = fa[x][i];
40 }
41 if (x == y) return x;
42 for (int i = 30; i >= 0; i--) {
43 if (fa[x][i] != fa[y][i]) {
44 x = fa[x][i];
45 y = fa[y][i];
46 }
47 }
48
49 return fa[x][0];
50 }
51
52 int main() {
53
54 int n, m, s;
55 cin >> n >> m >> s;
56 for (int i = 1; i < n; i++) {
57 int u, v;
58 cin >> u >> v;
59 G[u].push_back(v);
60 G[v].push_back(u);
61 }
62 dfs(s, 0);
63 for (; m; --m) {
64 int x, y;
65 cin >> x >> y;
66 cout << lca(x, y) << "\n";
67 }
68
69 return 0;
70 }