编程知识 cdmana.com

【算法小结】倍增算法求LCA

pre文章:倍增算法入门 超详细解答+LCA+RMQ(ST表)+例题剖析_繁凡さん的博客-CSDN博客_倍增算法

配套题目:

【模板】最近公共祖先(LCA) - 洛谷

代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
struct node {
	int v, ne;
}e[N<<1];
int head[N], cnt, lg[N], fa[N][30], depth[N];
void add(int x, int y) {
	e[++cnt].v = y;
	e[cnt].ne = head[x];
	head[x] = cnt;
}
void dfs(int now, int fath) {
	fa[now][0] = fath; depth[now] = depth[fath] + 1;
	for (int i = 1; i <= lg[depth[now]]; i++) fa[now][i] = fa[fa[now][i - 1]][i - 1];
	for (int i = head[now]; i != 0; i = e[i].ne) {
		if (e[i].v != fath) dfs(e[i].v, now);
	}
}
int LCA(int x, int y) {
	if (depth[x] < depth[y]) swap(x, y);
	while (depth[x] > depth[y]) x = fa[x][lg[depth[x] - depth[y]]];
	if (x == y) return x;
	for (int k = lg[depth[x]]; k >= 0; k--) {
		if (fa[x][k] != fa[y][k]) x = fa[x][k], y = fa[y][k];
	}
	return fa[x][0];
}
int main() {
	int n, m, s; cin >> n >> m >> s;
	for (int i = 1; i <= n - 1; i++) {
		int u, v; cin >> u >> v;
		add(u, v), add(v, u);
	}
	lg[0] = -1; for (int i = 1; i <= n; i++) lg[i] = lg[i >> 1] + 1;
	dfs(s, 0);
	for (int i = 1; i <= m; i++) {
		int x, y; cin >> x >> y;
		cout << LCA(x, y) << endl;
	}
	return 0;
}

版权声明
本文为[Ctrl AC]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_62434776/article/details/126139962

Scroll to Top