#include<bits/stdc++.h>
using namespace std;
const int maxn=500003;
vector s[maxn];
int f[maxn];
int d[maxn];
int size[maxn];
int top[maxn];
int son[maxn];
void dfs1(int x,int father)
{
size[x]=1;
d[x]=d[father]+1;
son[x]=0;
f[x]=father;
for(int i=0; i<s[x].size(); i++)
{
int to=s[x][i];
if(to==father)
continue;
dfs1(to,x);
size[x]+=size[to];
if(size[son[x]]<size[to])
son[x]=to;
}
}
void dfs2(int x,int topx)
{
top[x]=topx;
if(son[x]!=0)
dfs2(son[x],topx);
for(int i=0; i<s[x].size(); i++)
{
if(s[x][i]!=f[x]&&s[x][i]!=son[x])
{
dfs2(s[x][i],s[x][i]);
}
}
}
int lca(int x,int y)
{
while(top[x]!=top[y])
{
if(d[top[x]]<d[top[y]])
swap(x,y);
x=f[top[x]];
}
return d[x]<d[y]?x:y;
}
void add(int a,int b)
{
s[a].push_back(b);
s[b].push_back(a);
}
int main()
{
int n,m,root;
cin>>n>>m>>root;
for(int i=1; i<n; i++)
{
int u,v;
cin>>u>>v;
add(u,v);
}
dfs1(root,0);
dfs2(root,root);
for(int i=1; i<=m; i++)
{
int f;
int g;
cin>>f>>g;
int p=lca(f,g);
cout<<p<<endl;
}
return 0;
}
树链剖分(求LCA
最新推荐文章于 2024-07-12 18:56:03 发布