0pts悬关
查看原帖
0pts悬关
1046223
a_blue_fool楼主2024/4/28 14:20
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

vector <int> tree[5000005];
int n , m , s , x , y , depth[500005], f[500005][30] , log2n;

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

int LCA (int a , int b)
{
	if (depth[a] < depth[b]) swap(a,b);
	
	int d = depth[a] - depth[b];
	
	for (int i = 0 ; i <= log2n ; i++)
		if ((1<<i) & d) a = f[a][i];
	
	if (a == b) return a;
	
	for (int i = log2n ; i >= 0 ; i--)
	{
		if (f[a][i] == f[b][i]) continue;
		a = f[a][i] , b = f[b][i];
	}
	
	return f[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);
	}
	log2n = log2(n)+1;
	
	dfs(s , 0);
	
	for (int i = 1 ; i <= m ; i++)
	{
		scanf("%d%d" , &x , &y);
		printf("ans:%d\n" , LCA(x,y));
	}
	
	return 0;
}
2024/4/28 14:20
加载中...