先上模板把,原理有空再补
#include<bits/stdc++.h>
#include<bitset>
#include<unordered_map>
#define pb push_back
#define bp __builtin_popcount
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e6+100;
const int MOD=1e9+7;
int lowbit(int x){return x&-x;}
inline ll dpow(ll a, ll b){ ll r = 1, t = a; while (b){ if (b & 1)r = (r*t) % MOD; b >>= 1; t = (t*t) % MOD; }return r; }
inline ll fpow(ll a, ll b){ ll r = 1, t = a; while (b){ if (b & 1)r = (r*t); b >>= 1; t = (t*t); }return r; }
int depth[500001], fa[500001][22], lg[500001];
struct node{
int to,next;
}edge[maxn*3];
int head[maxn],tol;
void add(int a,int b)//链式前向星存图
{
edge[++tol].to=b;
edge[tol].next=head[a];
head[a]=tol;
}
void dfs(int u,int v)//v是u的爸爸!
{
fa[u][0]=v;depth[u]=depth[v]+1;
for(int i=1;i<=lg[depth[u]];i++)
fa[u][i]=fa[fa[u][i-1]][i-1];
for(int i=head[u];i;i=edge[i].next)
{
node t=edge[i];
if(t.to==v)//爸爸除外!
continue;
dfs(t.to,u);
}
}
int LCA(int x,int y)
{
if(depth[x]<depth[y])
{
swap(x,y);
}
while(depth[x]>depth[y])
{
x=fa[x][lg[depth[x]-depth[y]]-1];
}
if(x==y)return x;
for(int k=lg[depth[x]];k>=0;k--)
{
if(fa[x][k]!=fa[y][k])
{
x=fa[x][k];
y=fa[y][k];
}
}
return fa[x][0];
}
int main()
{
ios::sync_with_stdio(false);
int n,m,s;
cin>>n>>m>>s;
for(int i=1;i<n;i++)
{
int x,y;
cin>>x>>y;
add(x,y);
add(y,x);
}
for(int i = 1; i <= n; ++i)
lg[i] = lg[i-1] + (1 << lg[i-1] == i);
dfs(s,0);
for(int i=1;i<=m;i++)
{
int x,y;
cin>>x>>y;
cout<<LCA(x,y)<<endl;
}
system("pause");
return 0;
}