LCA求调,样例过不去
查看原帖
LCA求调,样例过不去
804607
rainygame楼主2023/4/29 17:27
#include <bits/stdc++.h>
using namespace std;
#define MAXN 500001
#define MAXK 21

int n, m, a, b, s;
int dep[MAXN];
int fa[MAXN][MAXK];
vector<int> e[MAXN];

void dfs(int x, int f){
	fa[x][0] = f;
	dep[x] = dep[f] + 1;
	for (int i=1; i<MAXK; i++) fa[x][i] = fa[fa[x][i-1]][i-1];
	for (auto v: e[x]){
		if (v == f) continue;
		dfs(v, x);
	}
}

int LCA(int x, int y){
	if (dep[x] < dep[y]) swap(x, y);
	for (int i=MAXK-1; i>=0; i--){
		if (dep[fa[x][i]] >= dep[y]) x = fa[x][i];
	}
	if (x == y) return x;
	for (int i=MAXK-1; i>=0; i--){
		if (fa[x][i] != fa[y][i]){
			x = fa[x][i];
			y = fa[y][i];
		}
	}
	
	return fa[x][0];
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	
	cin >> n >> m >> s;
	for (int i=1; i<n; i++){
		cin >> a >> b;
		e[a].push_back(b);
		e[b].push_back(a);
	}
	dfs(1, 0);
	
	while (m--){
		cin >> a >> b;
		cout << LCA(a, b) << '\n';
	}
	
	return 0;
}

2023/4/29 17:27
加载中...