LCA
LCA总结
最近公共祖先(Lowest Common Ancestor, LCA)是树结构中的一个经典问题。
1. LCA 问题定义
给定一棵有根树
示例:
1
/ \
2 3
/ \ \
4 5 6
- LCA(4, 5) = 2
- LCA(4, 6) = 1
- LCA(3, 6) = 3
2. 常见 LCA 算法
(1) 暴力跳转法(Brute Force)
思路:
- 先让较深的节点向上跳,直到两个节点深度相同。
- 然后两个节点一起向上跳,直到相遇。
时间复杂度:
- 预处理:无(直接遍历树计算深度)。
- 查询:
O(h) ,其中h 是树的高度(最坏情况O(n) )。
适用场景:
- 适用于树结构较平衡的情况。
- 实现简单,但查询效率较低。
代码示例(C++):
int getLCA(int u, int v) {
while (u != v) {
if (depth[u] > depth[v]) u = fa[u];
else v = fa[v];
}
return u;
}
(2) 二进制跳跃法(Binary Lifting)
思路:
- 预处理每个节点的
2^k 级祖先(类似 ST 表)。 - 查询时,先调整深度,再用二进制跳跃快速找到 LCA。
时间复杂度:
- 预处理:
O(n \log n) (计算每个节点的2^k 级祖先)。 - 查询:
O(\log n) 。
适用场景:
- 适用于多次查询的情况。
代码示例(C++):
#include<bits/stdc++.h>
#define endl '\n'
#define ABC cin.tie(0)->sync_with_stdio(0);
using namespace std;
const int N=5e5+5;
int n,m,s,head[N],idx,f[N][25],dept[N];
struct node{
int v,nxt;
}a[N*2];
void add(int u,int v){
a[++idx]={v,head[u]};
head[u]=idx;
}
void dfs(int u,int fa){
dept[u]=dept[fa]+1;
for(int i=head[u];i;i=a[i].nxt){
int v=a[i].v;
if(v==fa)continue;
f[v][0]=u;
dfs(v,u);
}
}
int lca(int u,int v){
if(dept[v]>dept[u]) swap(u,v);
for(int i=20;i>=0;i--)
if(dept[f[u][i]]>=dept[v]) u=f[u][i];
if(u==v) return v;
for(int i=20;i>=0;i--)
if(f[u][i]!=f[v][i]) u=f[u][i],v=f[v][i];
return f[u][0];
}
int main(){ABC
cin>>n>>m>>s;
for(int i=1;i<n;i++){
int u,v;
cin>>u>>v;
add(u,v),add(v,u);
}
dfs(s,0);
for(int i=1;i<=20;i++){
for(int j=1;j<=n;j++){
f[j][i]=f[f[j][i-1]][i-1];
}
}
while(m--){
int x,y;
cin>>x>>y;
cout<<lca(x,y)<<endl;
}
return 0;
}