倍增80pts大佬求助啊
查看原帖
倍增80pts大佬求助啊
929151
xxr___楼主2023/11/17 20:00
#include<iostream>
#include<algorithm>
using std::cin;
using std::cout;
using std::swap;
const int N=5e5+5;

int n,m,s,u,v,i,j,k,l,r,d[N],fa[N][20],cnt=0,hd[N];
struct node{
	int to,next;
}e[N<<1];
void init(){
	for(i=0;i<(n<<1);++i){
		e[i].next=-1;hd[i]=-1;
	}
}
void add(int u,int v){
	e[cnt].to=v;
	e[cnt].next = hd[u];
	hd[u]=cnt++;
}
void dfs(int x,int f){
	d[x]=d[f]+1;
	fa[x][0]=f;
	for(i=1;(1<<i)<=d[x];++i){
		fa[x][i] = fa[fa[x][i-1]][i-1];
	}
	for(i=hd[x];i!=-1;i=e[i].next){
		if(e[i].to!=f){
			dfs(e[i].to,x);
		}
	}
}

	
int lca(int x,int y){
	if(d[x]<d[y]) swap(x,y);
	for(i=19;i>=0;--i){
		if(d[x]-(1<<i)>=d[y]){
			x=fa[x][i];
		}
	}
	if(x==y) return x;
	for(i=19;i>=0;--i){
		if(fa[x][i]!=fa[y][i]){
			x=fa[x][i],y=fa[y][i];
		}
	}
	return fa[x][0];
}
int main(){
	init();
	int root;
	cin>>n>>m>>root;
	for(i=1;i<n;++i){
		cin>>u>>v;
		add(u,v);add(v,u);
	}
	dfs(root,0);
	while(m--){
		cin>>u>>v;
		cout<<lca(u,v)<<'\n';
	}
}
2023/11/17 20:00
加载中...