0pts求助
查看原帖
0pts求助
1046223
a_blue_fool楼主2024/3/29 13:54
#include <bits/stdc++.h>

using namespace std;

int n , m , s , x , y , depth[500001] , fa[500001][30];

vector <int> tree[500001];

void dfs (int x , int father)
{
	fa[x][0] = father; 
	depth[x] = depth[father]+1;
	
	for (int i = 1 ; i <= log2(depth[x]) ; i++)
		fa[x][i] = fa[fa[x][i-1]][i-1];
	
	for (auto i : tree[x])
		if (i != father)
			dfs (i , x);
	
	return;
}

int lca (int a , int b)
{
	if (depth[a] < depth[b]) swap(a , b);
	
	while (depth[a] > depth[b]) 
		a = fa[a][(int)log2(depth[a] - depth[b]) - 1];
	
	if (a == b) return a;
	
	for (int i = log2(depth[a]) - 1 ; i >= 0 ; i--)
		if (fa[a][i] != fa[b][i])
			a = fa[a][i] , b = fa[b][i];
	
	return fa[a][0];
}

int main()
{
	scanf("%d%d%d" , &n , &m , &s);
	
	for (int i = 1 ; i < n ; i++)
	{
		scanf("%d%d" , &x , &y);
		tree[x].push_back(y);
		tree[y].push_back(x);
	}
	
	dfs(s , 0);
	
	for (int i = 1 ; i <= m ; i++)
	{
		scanf("%d%d" , &x , &y);
		printf("%d\n" , lca(x , y));
	}
	
	return 0;
}
2024/3/29 13:54
加载中...