【洛谷P3379】【lca】【树链剖分】

【链接】

https://www.luogu.org/problemnew/show/P3379

【题意】

求lca

【代码】

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 6;
vector<int>v[maxn];
int a[maxn];
int deep[maxn];
int fa[maxn];
int tot[maxn];
int top[maxn];
int son[maxn];

int dfs1(int now, int f, int dep) {
	deep[now] = dep;
	fa[now] = f;
	tot[now] = 1;
	int maxson = -1;
	for (int x : v[now]) {
		if (x == f)continue;
		tot[now] += dfs1(x, now, dep + 1);
		if (tot[x] > maxson) {
			maxson = tot[x];
			son[now] = x;
		}
	}
	return tot[now];
}

void dfs2(int now, int topf) {
	top[now] = topf;
	if (!son[now])return;
	dfs2(son[now], topf);
	for (int x : v[now]) {
		if (x != son[now] && x != fa[now]) {
			dfs2(x, x);
		}
	}
}

int lca(int x, int y) {
	while (top[x] != top[y]) {
		if (deep[top[x]] < deep[top[y]])swap(x, y);
		x = fa[top[x]];
	}
	if (deep[x] > deep[y])swap(x, y);
	return x;
}

int main() {
	int n, m, root;
	scanf("%d%d%d", &n, &m, &root);
	for (int i = 1; i < n; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		v[x].push_back(y);
		v[y].push_back(x);
	}
	dfs1(root, 0, 1);
	dfs2(root, root);
	while (m--) {
		int x, y;
		scanf("%d%d", &x, &y);
		printf("%d\n", lca(x, y));
	}
}

猜你喜欢

转载自blog.csdn.net/running_acmer/article/details/82963328