最近公共祖先(LCA)
作者:互联网
luogu 模板:https://www.luogu.com.cn/problem/P3379
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int n, m, root, d[N], p[N][30], lg[N];
vector <int> g[N];
void dfs(int u, int fa){
p[u][0] = fa;
d[u] = d[fa] + 1;
for (int i = 1; i <= lg[d[u]]; i ++ )
p[u][i] = p[p[u][i - 1]][i - 1];
// u 的 2^i 的祖先等于 u 的 2^(i-1) 的祖先的 2^(i-1) 的祖先
for (auto v : g[u])
if (v != fa)
dfs(v, u);
}
int lca(int x, int y){
if(d[x] < d[y]) swap(x, y);
while (d[x] > d[y])
x = p[x][lg[d[x] - d[y]] - 1];
if (x == y) return x;
for (int k = lg[d[x]] - 1; k >= 0; k -- )
if (p[x][k] != p[y][k]){
x = p[x][k];
y = p[y][k];
}
return p[x][0];
}
int main(){
ios::sync_with_stdio(false);cin.tie(0);
cin >> n >> m >> root;
for (int i = 1; i < n; i ++ ){
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
for (int i = 1; i <= n; i ++ ) //预处理 log
lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
dfs(root, 0); //找到每个点的祖先
for (int i = 1; i <= m; i ++ ){
int x, y;
cin >> x >> y;
cout << lca(x, y) << "\n";
}
return 0;
}
标签:lg,return,fa,祖先,luogu,LCA,cin,int,公共 来源: https://www.cnblogs.com/Hamine/p/16191722.html