其他分享
首页 > 其他分享> > 【LCA】【施工中】

【LCA】【施工中】

作者:互联网

#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 +5;
int h[N],ne[N<<1],e[N<<1],fa[N<<1][22],lg[N<<1],dep[N],idx,n,m,s;

inline void add(int x,int y){e[++idx] = y,ne[idx] = h[x];h[x] = idx;}

void dfs(int u,int f)
{
	fa[u][0] = f;dep[u] = dep[f] + 1;
	for(int i = 1 ; i <= lg[dep[u]] ; i ++)
	fa[u][i] = fa[fa[u][i - 1]][i - 1];
	for(int i = h[u];i;i = ne[i])
	if(e[i] != f)dfs(e[i],u);
}

int lca(int x,int y)
{
	if(dep[x] < dep[y])swap(x,y);
	while(dep[x] > dep[y])x = fa[x][lg[dep[x] - dep[y]] - 1];
	if(x == y )return x; 
	for(int k = lg[dep[x]] - 1; k >= 0 ; k --)
	if(fa[x][k] != fa[y][k])
	x = fa[x][k],y = fa[y][k];
	return fa[x][0];
}

int main()
{
	//freopen("P3379.in","r",stdin);
	cin >> n >> m >> s;
	for(int x,y,i = 1; i <= n -1 ; i ++ )
	{
		scanf("%d%d",&x,&y);
		add(x,y),add(y,x);
	}

	for(int i = 1 ; i <= n ; i ++)
	lg[i] = lg[i - 1] + (1 << lg[i - 1] == i );

	dfs(s,0);

	while(m--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		printf("%d\n",lca(x,y));
	}
}

标签:std,lg,return,int,施工,fa,LCA,dep
来源: https://www.cnblogs.com/ErFu/p/16486750.html