蒟蒻求调倍增LCA
查看原帖
蒟蒻求调倍增LCA
236416
_stOrz_楼主2021/7/6 17:34
#include<bits/stdc++.h>

#define N 100005

using namespace std;

int n,m,s,cnt,head[N],fa[N][20],dep[N],lg[N],maxd;
struct node{
	int to,next,dis;
}k[10005];

inline int read()
{
	char ch=getchar();int s=0;bool f=false;
	while((ch<'0' or ch>'9') and ch!='-')
	ch=getchar();
	if(ch=='-') f=true,ch=getchar();
	while(ch<='9' and ch>='0')
	s=s*10+ch-48,ch=getchar();
	return f?-s:s;
}

inline void add(int a,int b)
{
	k[++cnt].to=b;
	k[cnt].dis=1;
	k[cnt].next=head[a];
	head[a]=cnt;
}

inline void dfs(int now,int f)
{
	fa[now][0]=f;
	dep[now]=dep[f]+1;
	for(int i=1;i<=lg[dep[now]];i++)
		fa[now][i]=fa[fa[now][i-1]][i-1];
	for(int i=head[now];i;i=k[i].next)
		if(k[i].to != f) {
			dfs(k[i].to,now);
		}	
}

inline int LCA(int x,int y)
{
	if(dep[x]<dep[y]) swap(x,y);
	for(int i=20;i>=0;i--)
		if(dep[x]-(1<<i)>=dep[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()
{
	n=read(),m=read(),s=read();
	for(int i=1;i<=n-1;i++){
		int a,b;
		a=read(),b=read();
		add(a,b);
		add(b,a);
	}
	lg[0]=1;
	for(int i=1;i<=n;i++)
		lg[i]=lg[i>>1]+1;
	dfs(s,0);
	for(int i=1;i<=m;i++)
	{
		int x,y;
		x=read(),y=read(); 
		cout<<LCA(x,y)<<"\n";
	}
	return 0;
}




2021/7/6 17:34
加载中...