P3379 【模板】最近公共祖先(LCA)

题目传送门:https://www.luogu.com.cn/problem/P3379

倍增LCA模板:

 1 #include
 2 #include
 3 #include
 4 #include
 5 #include
 6 #include
 7 #include<set>
 8 #include
 9 #include
10 #include
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)  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 }

永远热爱,永远向着光。

Original: https://www.cnblogs.com/wabi/p/16520311.html
Author: Kyrizer_W
Title: P3379 【模板】最近公共祖先(LCA)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/587882/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球