题解:P3379 【模板】最近公共祖先(LCA)
upd:2025.4.20 更新了一处笔误。
最近公共祖先(LCA,Lowest Common Ancestor)
定义
如果有两个点
求解
- 暴力做法(无预处理,查询
O(n) )
首先从
- 倍增做法(预处理
O(n \log n) ,查询O(\log n) )
- 预处理
我们定义
还要预处理出每个节点的深度。
然后就是对倍增进行更新。
我们知道:
也就是从上一级转移过来(
那么初始值就是
- 查询
我们定义
那么,我们可以从大到小枚举跳的幂次,如果跳了这么多后,
跳完后,判断两个是不是相等,因为有可能
然后,只要跳上去后
void Search(int u, int fa) // 预处理
{
dep[u] = dep[fa] + 1, f[u][0] = fa; // 处理深度,及f的初始化
for (int i = 1; i <= 20; ++i) f[u][i] = f[f[u][i - 1]][i - 1]; // 转移
for (int v : g[u]) if (v != fa) Search(v, u); // 下一个
return;
}
int query(int x, int y) // 查询
{
if (dep[x] < dep[y]) swap(x, y); // 满足上述规则
for (int i = 20; i >= 0; --i) if (dep[f[x][i]] >= dep[y]) x = f[x][i]; // 跳到和y深度一样
if (x == y) return x; // 特判
for (int i = 20; i >= 0; --i) if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i]; // 再一起跳
return f[x][0]; // 返回答案
}
完整代码
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
#include <string>
#include <vector>
#include <cstring>
#include <bitset>
#define int long long
using namespace std;
const int N = 5e5 + 5, INF = 1e18;
int n, q, s, dep[N], f[N][25];
vector<int> g[N];
void Search(int u, int fa)
{
dep[u] = dep[fa] + 1, f[u][0] = fa;
for (int i = 1; i <= 20; ++i) f[u][i] = f[f[u][i - 1]][i - 1];
for (int v : g[u]) if (v != fa) Search(v, u);
return;
}
int query(int x, int y)
{
if (dep[x] < dep[y]) swap(x, y);
for (int i = 20; i >= 0; --i) if (dep[f[x][i]] >= dep[y]) x = f[x][i];
if (x == y) return x;
for (int i = 20; i >= 0; --i) if (f[x][i] != f[y][i]) x = f[x][i], y = f[y][i];
return f[x][0];
}
signed main()
{
cin.tie(0)->sync_with_stdio(false);
cin >> n >> q >> s;
for (int i = 1, x, y; i < n; ++i)
{
cin >> x >> y;
g[x].emplace_back(y), g[y].emplace_back(x);
}
Search(s, 0);
for (int x, y; q--; cout << '\n')
{
cin >> x >> y;
cout << query(x, y);
}
return 0;
}
麻烦管理重新审核一下