P3379 【模板】最近公共祖先(LCA)
题目传送门: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 }
永远热爱,永远向着光。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!