树剖UKE求助
查看原帖
树剖UKE求助
678507
shenming101楼主2023/11/13 07:46
#include<bits/stdc++.h>
using namespace std;
const int N=500005;
struct node{
	int to,next;
}edge[N*2];
int head[N],cnt,dfn[N],deep[N],fa[N],son[N],tot[N],top[N];
void addege(int u,int v){
	edge[++cnt].to=v;
	edge[cnt].next=head[u];
	head[u]=cnt;
}
void dfs1(int x,int f,int d){
	deep[x]=d;
	fa[x]=f;
	tot[x]=1;
	int maxson=-1;
	for(int i=head[x];i;i=edge[i].next){
		int y=edge[i].to;
		if(y==f) continue;
		dfs1(y,x,d+1);
		tot[x]+=tot[y];
		if(tot[y]>maxson){
			maxson=tot[y];
			son[x]=y;
		}
	}
	return;
}
void dfs2(int x,int topfa){
	top[x]=topfa;
	if(son[x]==0) return;
	dfs2(son[x],topfa);
	for(int i=head[x];i;i=edge[i].next){
		int y=edge[i].to;
		if(y==fa[x]||y==son[x]) continue;
		dfs2(y,y);
	}
	return;
}
int main(){
	int n,m,s;
	scanf("%d%d%d",&n,&m,&s);
	for(int i=1;i<=n-1;i++){
		int x,y;
		scanf("%d%d",&x,&y);
		addege(x,y);
		addege(y,x);
	}
	dfs1(s,0,1);
	dfs2(s,s);
	for(int i=1;i<=m;i++){
		int x,y;
		cin >> x >> y;
		while(top[x]!=top[y]){
			if(deep[top[x]]>=deep[top[y]]){
				x=fa[top[x]];
			}else{
				y=fa[top[y]];
			} 
		}
		if(deep[x]<deep[y]){
			printf("%d\n",x);
		}else{
			printf("%d\n",y);
		}
	}
	return 0;
}
2023/11/13 07:46
加载中...