全部超时了
查看原帖
全部超时了
1120050
qj2zyzj楼主2024/5/17 13:55
#include <bits/stdc++.h>
using namespace std;
const long long N=500005;
int fst[N],to[N*2],nex[N*2],tot,dep[N],fa[N];
void add(int x,int y){
	to[++tot]=y;
	nex[tot]=fst[x];
	fst[x]=tot;
}
void dfs(int x,int f){
	fa[x]=f;
	dep[x]=dep[f]+1;
	for(int i=fst[x];i;nex[i]){
		if(to[i]!=f) dfs(to[i],x);
	}
}
int lca(int x,int y){
	if(dep[y]>dep[x]) swap(x,y); 
	while(dep[x]>dep[y]) x=fa[x];
	while(x!=y){
		x=fa[x];
		y=fa[y];
	}
	return x;
}
int main(){
// 	freopen("data.in.cpp","r",stdin);
	int n,m,root;
	cin>>n>>m>>root;
	for(int i=1;i<n;i++){
		int x,y;
		cin>>x>>y;
		add(x,y);
		add(y,x);
	}
	dfs(root,root);
	while(m--){
		int l,r;
		cin>>l,r;
		cout<<lca(l,r)<<endl;
	}
	return 0;
}
2024/5/17 13:55
加载中...