第3版过样例了,但0分全re,求调
查看原帖
第3版过样例了,但0分全re,求调
1349423
jms23002楼主2025/1/16 15:07
#include<bits/stdc++.h>
using namespace std;
const int N=5e5+5;
struct node{
	int yl;
	int ee;
	int nxt;
}e[N];
int n,k;
int head[N],deep[N],idx,s;
int f[N][25];
void add(int a, int b){
    e[idx].ee = b;
    e[idx].nxt = head[a];
    head[a] = idx++;
}
void dfs(int u,int fa){
	deep[u]=deep[fa]+1;
	f[u][0]=fa;
	for(int i=1;i<=22;i++){
		f[u][i]=f[f[u][i-1]][i-1];
	}
	for(int i=head[u];i!=-1;i=e[i].nxt){
		int v=e[i].ee;
		if(v!=fa){
			deep[v]=deep[u]+1;
			dfs(v,u);
		} 
	}
}
int lca(int x,int y){
	if(deep[x]<deep[y]) swap(x,y);
	for(int i=22;i>=0;i--){
		if(deep[y]>=deep[f[x][i]]){
			x=f[x][i];
		}
	}
	if(x==y) return x;
	for(int i=22;i>=0;i--){
		if(f[x][i]!=f[y][i]){
			x=f[x][i];
			y=f[y][i];
		}
	}
	return f[x][0];
}
int main(){
	memset(head,-1,sizeof head);
	cin>>n>>k>>s;
	for(int i=1;i<n;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		add(x,y);
		add(y,x);
	}
	dfs(s,-1);
	for(int i=1;i<=k;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		int ans=lca(x,y);
		cout<<ans<<endl;
	}
	return 0;
}
2025/1/16 15:07
加载中...