8 TLE 9wa 求助大佬
查看原帖
8 TLE 9wa 求助大佬
570507
witw楼主2022/2/4 14:02
#include<iostream>
#include<cstring>
using namespace std;
const int N=5e+5;
int h[2*N],ne[2*N],e[2*N],idx;
int fa[N][21],depth[N];
void add(int x,int y){
	e[idx]=x,ne[idx]=h[y],h[y]=idx++;
}
void dfs(int now,int father){
	fa[now][0]=father;depth[now]=depth[father]+1;
	for(int i=1;(1<<i)<=depth[now];i++)fa[now][i]=fa[fa[now][i-1]][i-1];
	for(int i=h[now];i!=-1;i=ne[i]){
		int k=e[i];
		if(k==father)continue;
		dfs(k,now);
	}
}
int LCA(int x,int y){
	if(depth[x]<depth[y])swap(x,y);
	for(int i=20;i>=0;i--){
		if(depth[fa[x][i]]>=depth[y])x=fa[x][i];
		if(x==y)return x;
	}
	for(int i=20;i>=0;i--){
		if(fa[x][i]!=fa[y][i]){
			x=fa[x][i],y=fa[y][i];
		}
	}
	return fa[x][0];
} 
int main(){
	int n,m,s;
	memset(h,-1,sizeof h);
	cin>>n>>m>>s;
	for(int i=1;i<n;++i){
		int x,y;
		cin>>x>>y;
		add(x,y);
		add(y,x);
	}
	dfs(s,0);
	for(int i=1;i<=m;i++){
		int x,y;
		cin>>x>>y;
		cout<<LCA(x,y)<<endl;
	}
	return 0;
} 
2022/2/4 14:02
加载中...