#include<bits/stdc++.h>
#define int long long
#define maxn 500100
using namespace std;
int n,m,s;
int tot=0,cnt=0;
int head[2*maxn],nxt[2*maxn],to[2*maxn];
int d[maxn],f[30][2*maxn];
inline int read(){
char ch=getchar();
int x=0,cf=1;
while(ch<'0' || ch>'9'){
if(ch=='-') cf=-1;
ch=getchar();
}
while(ch>='0' && ch<='9'){
x=(x<<3)+(x<<1)+(ch^48);
ch=getchar();
}
return x*cf;
}
void add(int u,int v){
nxt[++cnt]=head[u];
head[u]=cnt;
to[cnt]=v;
}
void dfs(int u,int dep){
d[u]=dep;
for(int i=head[u];i!=-1;i=nxt[i]){
int v=to[i];
if(!d[v]) dfs(v,dep+1),f[0][v]=u;
}
}
int lca(int x,int y){
int l=0;
while((1<<l)<=n) l++;
l--;
if(d[x]<d[y]) swap(x,y);
for(int i=20;i>=0;i--) if(d[y]<=d[x]-(1<<i)) x=f[i][x];
if(x==y) return x;
for(int i=20;i>=0;i--) if(f[i][x]!=f[i][y]) x=f[i][x],y=f[i][y];
return f[0][x];
}
signed main(){
// ios::sync_with_stdio(false);
// cin.tie(0);cout.tie(0);
memset(head,-1,sizeof head);
n=read(),m=read(),s=read();
// cin>>n>>m>>s;
// scanf("%lld %lld %lld",&n,&m,&s);
for(int i=1;i<n;i++){
int u=read(),v=read();
// cin>>u>>v;
// scanf("%lld %lld",&u,&v);
add(u,v);add(v,u);
}
f[0][s]=s,dfs(s,1);
for(int i=1;(1<<i)<=n;i++) for(int j=1;j<=n;j++) f[i][j]=f[i-1][f[i-1][j]];
for(int i=1;i<=m;i++){
int u=read(),v=read();
// cin>>u>>v;
int ans=lca(u,v);
cout<<ans<<endl;
// printf("%lld\n",ans);
}
return 0;
}
#include<bits/stdc++.h>
#define int long long
#define maxn 500100
using namespace std;
int n,m,s;
int tot=0,cnt=0;
int head[2*maxn],nxt[2*maxn],to[2*maxn];
int d[maxn],f[30][2*maxn];
void add(int u,int v){
cnt++;
nxt[cnt]=head[u];
head[u]=cnt;
to[cnt]=v;
}
void dfs(int u,int dep){
d[u]=dep;
for(int i=head[u];i!=-1;i=nxt[i]){
int v=to[i];
if(!d[v]) dfs(v,dep+1),f[0][v]=u;
}
}
int lca(int x,int y){
int l=0;
while((1<<l)<=n) l++;
l--;
if(d[x]<d[y]) swap(x,y);
for(int i=20;i>=0;i--) if(d[y]<=d[x]-(1<<i)) x=f[i][x];
if(x==y) return x;
for(int i=20;i>=0;i--) if(f[i][x]!=f[i][y]) x=f[i][x],y=f[i][y];
return f[0][x];
}
signed main(){
memset(head,-1,sizeof head);
scanf("%lld %lld %lld",&n,&m,&s);
for(int i=1;i<n;i++){
int a,b;
scanf("%lld %lld",&a,&b);
add(a,b),add(b,a);
}
f[0][s]=s,dfs(s,1);
for(int i=1;(1<<i)<=n;i++) for(int j=1;j<=n;j++) f[i][j]=f[i-1][f[i-1][j]];
for(int i=1;i<=m;i++){
int a,b;
scanf("%lld %lld",&a,&b);
int ans=lca(a,b);
printf("%lld\n",ans);
}
return 0;
}
这两份代码有区别吗?为什么上边的过不了,艹