30pts
查看原帖
30pts
924402
yangjinqian楼主2024/12/5 16:07
#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int n, m, root;
vector<int> a[N];
int father[N][30];
int dep[N], lg[N];
void build(int u, int fa){
	dep[u] = dep[fa] + 1, father[u][0] = fa;
	for (int i = 1; i <= lg[dep[u]] + 1; i++) father[u][i] = father[father[u][i - 1]][i - 1];
	for (int i = 0; i < a[u].size(); i++)
		if (a[u][i] != fa)
			build(a[u][i], u);
}
int LCA(int x, int y){
	if (dep[x] < dep[y]) swap(x, y);
	while (dep[x] != dep[y]) x = father[x][lg[dep[x] - dep[y]]];
	if (x == y) return x;
	for (int i = lg[dep[x]]; i >= 0; i--)
		if (father[x][i] != father[y][i])
			x = father[x][i], y = father[y][i];
	return father[x][0];
}
int main(){
	ios::sync_with_stdio(0); 
	cin.tie(0);
	cout.tie(0);
	cin >> n >> m >> root;
	for (int i = 2; i <= N - 10; i++) lg[i] = lg[i] / 2 + 1;
	for (int i = 1; i < n; i++){
		int x, y;
		cin >> x >> y;
		a[x].push_back(y); 
		a[y].push_back(x);
	}
	build(root, 0);
	while (m--){
		int x, y;
		cin >> x >> y;
		cout << LCA(x, y) << endl;
	}
	return 0;
}
2024/12/5 16:07
加载中...