最近公共祖先 Tarjan算法

发布时间 2023-09-24 19:36:13作者: 不o凡

P3379 【模板】最近公共祖先(LCA)

利用并查集

点击查看代码
#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
vector<int> g[N];
vector<pair<int,int>> query[N];
int ans[N],vis[N];
int f[N];
int find(int x) {
	return f[x] == x ? x : f[x] = find(f[x]);
}
void taryan(int u,int father) {
	vis[u] = 1;//标记
	for (auto v : g[u]) {
		if (v == father) continue;
		taryan(v, u);
		f[v] = u;//回u时,v指向u
	}
	//离u时,枚举LCA
	for (auto v : query[u]) {
		int i = v.second, t = v.first;
		if (vis[t]) ans[i] = find(t);
	}
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int n, m, S;
	cin >> n >> m >> S;
	for (int i = 1; i <= n; i++) f[i] = i;
	for (int i = 1; i < n; i++) {
		int x, y;
		cin >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	for (int i = 1; i <= m; i++) {
		int a, b;
		cin >> a >> b;
		query[a].push_back({ b,i });
		query[b].push_back({ a,i });
	}
	taryan(S,0);
	for (int i = 1; i <= m; i++) {
		cout << ans[i] << '\n';
	}
	return 0;
}