whyWA20?
查看原帖
whyWA20?
743373
Vitamin_B楼主2024/3/24 19:40
# include <bits/stdc++.h>

# define ffor(i,name) \
	for (auto i = name.begin (); i != name.end (); ++ i)

using namespace std;

typedef long long ll;

typedef pair <int, int> pii;

int n, x, y, f[500005][25], depth[500005], m, rt;

vector <int> v[500005];

void init (int x) {

	for (int i = 1; i < 20; ++ i)
		f[x][i] = f[f[x][i - 1]][i - 1];

	for (int i : v[x])
		if (i != f[x][0])
			f[i][0] = x, depth[i] = depth[x] + 1, init (i);

	return ;

}

int lca (int a, int b) {

	if (depth[a] > depth[b])
		swap (a, b);

	x = depth[b] - depth[a];

	for (int i = 0; i < 20; ++ i)
		if (x & 1 << i)
			b = f[b][i];

	if (a == b)
		return a;

	for (int i = 19; ~i; -- i)
		if (f[a][i] != f[b][i])
			a = f[a][i], b = f[b][i];

	return f[a][0];

}

int main () {
//	freopen ("sample.in", "r", stdin);
//	freopen ("sample.out", "w", stdout);
	ios::sync_with_stdio (0);

	cin.tie (0);

	cout.tie (0);

	cin >> n >> m >> rt;

	for (int i = 1; i < n; ++ i)
		cin >> x >> y, v[x].emplace_back (y), v[y].emplace_back (x);

	init (rt);

	while (m --) {

		cin >> x >> y;

		cout << lca (x, y) << '\n';

	}

	return 0;

}
2024/3/24 19:40
加载中...