倍增算法
可以强制在线,也可以不强制在线。
#include<bits/stdc++.h>
using namespace std;
#define N 500001
int n,m,tot;
int h[N],nt[N<<1],to[N<<1];
void add(int u,int v)
{
nt[++tot]=h[u];
h[u]=tot;
to[tot]=v;
}
int d[N],f[N][23];
void dfs(int x,int fa)
{
d[x]=d[fa]+1;
f[x][0]=fa;
for(int i=1; i<=22; i++)
{
f[x][i]=f[f[x][i-1]][i-1];
if(f[x][i]==0)break;
}
for(int i=h[x],y; i; i=nt[i])
{
y=to[i];
if(y==fa)continue;
dfs(y,x);
}
}
int LCA(int x,int y)
{
if(d[x]<d[y])swap(x,y);
for(int i=22; i>=0; i--)
if(d[f[x][i]]>=d[y])x=f[x][i];
if(x==y)return x;
for(int i=22; i>=0; i--)
{
if(f[x][i]==f[y][i])continue;
x=f[x][i],y=f[y][i];
}
return f[x][0];
}
int root;
int main()
{
scanf("%d%d%d",&n,&m,&root);
for(int i=1,x,y; i<n; i++)
{
scanf("%d%d",&x,&y);
add(x,y);add(y,x);
}
dfs(root,0);
for(int j=1; j<=n; j++){for(int i=0; i<=11; i++)cout<<f[j][i]<<" ";cout<<endl;}
for(int i=1,x,y; i<=m; i++)
{
scanf("%d%d",&x,&y);
printf("%d\n",LCA(x,y));
}
return 0;
}
离线算法 – T a r j a n Tarjan Tarjan 算法
对于节点 x x x , x , y x , y x,y( y y y 已经遍历过)的最近公共祖先一定是 f i n d ( y ) find(y) find(y) 。
原因如下:
对于正在判断 L C A LCA LCA 的节点 x x x 。
x x x没有回溯,所以 f a [ x ] = x fa [ x ] = x fa[x]=x 。
对于以 x x x 为根的子树的任意一个节点 u u u ,有 f i n d ( u ) = x find(u)=x find(u)=x ,即 u u u 的祖先中还未回溯的节点是 x x x 。
-
当 y y y 是以 x x x 为根的子树的节点时, f i n d ( y ) find(y) find(y) 指向 x x x , x , y x,y x,y 的 L C A LCA LCA 是 x x x 。
-
当 y y y 是 x x x 的祖先时, f a [ y ] = y fa[y]=y fa[y]=y ,因为 y y y 节点还未回溯, x , y x,y x,y 的 L C A LCA LCA 是 y y y 。
-
当 y y y 既不是是以 x x x 为根的子树的节点,也不是以 x x x 的祖先时,因为 f i n d ( y ) find(y) find(y) 是指 y y y 的祖先中还未回溯的节点,该节点一定是从根节点到 x x x 路径中的节点(该路径中的节点还未回溯),该节点一定是 x , y x,y x,y 的共同祖先,并且 f i n d ( y ) find(y) find(y) 指向的是离 y y y 最近的节点 L C A ( x , y ) LCA(x,y) LCA(x,y) ,一定不是 L C A ( x , y ) LCA(x,y) LCA(x,y) 的祖先(因为 L C A ( x , y ) LCA(x,y) LCA(x,y) 比 L C A ( x , y ) LCA(x,y) LCA(x,y) 的祖先离 y y y 更近),所以 L C A ( x , y ) = f i n d ( y ) LCA(x,y)=find(y) LCA(x,y)=find(y) 。
#include<bits/stdc++.h>
using namespace std;
#define N 500001
vector < pair <int , int > > e[N];
int tot,h[N],to[N*2],nt[N*2];
int n,fa[N];
void add(int u,int v)
{
nt[++tot]=h[u];
h[u]=tot;
to[tot]=v;
}
void add_e(int x,int y,int i)
{
e[x].push_back(make_pair(y,i));
e[y].push_back(make_pair(x,i));
}
int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}
int d[N],v[N],len[N],lca[N*4];
void Tarjan(int x,int p)
{
d[x]=d[p]+1;
v[x]=1;
for(int i=h[x],y; i; i=nt[i])
{
y=to[i];
if(v[y])continue;
Tarjan(y,x);
fa[y]=x;
}
for(int i=0; i<e[x].size(); i++)
{
int y=e[x][i].first;
if(v[y])
{
lca[e[x][i].second]=find(y);
}
}
}
int m,root;
int main()
{
cin>>n>>m>>root;
for(int i=1; i<=n; i++)fa[i]=i;
for(int i=1,x,y; i<n; i++)
{
cin>>x>>y;
add(x,y);add(y,x);
}
for(int i=1,x,y; i<=m; i++)
{
cin>>x>>y;
add_e(x,y,i);
}
Tarjan(root,0);
for(int i=1; i<=m; i++)
{
cout<<lca[i]<<endl;
}
}