社区讨论
100pts TLE 求助
P3379【模板】最近公共祖先(LCA)参与者 2已保存回复 1
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 1 条
- 当前快照
- 1 份
- 快照标识符
- @mjnl1qig
- 此快照首次捕获于
- 2025/12/27 08:49 2 个月前
- 此快照最后确认于
- 2025/12/28 20:10 2 个月前
CPP
#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 5;
int father[maxn], head[maxn], head_query[maxn], ans[maxn], cnt_query, cnt;
bool vis[maxn];
struct Edge {
int to, next, num;
} edge[2 * maxn], query[2 * maxn];
void init() {
for (int i = 0; i < 2 * maxn; ++i) {
edge[i].next = -1;
head[i] = -1;
query[i].next = -1;
head_query[i] = -1;
}
cnt = 0;
cnt_query = 0;
}
void add(int u, int v) {
edge[cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt++;
}
void add_query(int x, int y,int num) {
query[cnt_query].to = y;
query[cnt_query].num = num;
query[cnt_query].next = head_query[x];
head_query[x] = cnt_query++;
}
int find_set(int x) {
return father[x] == x ? x : find_set(father[x]);
}
void Tarjan(int x) {
vis[x] = true;
for (int i = head[x]; ~i; i = edge[i].next) {
int y = edge[i].to;
if (!vis[y]) {
Tarjan(y);
father[y] = x;
}
}
for (int i = head_query[x]; ~i; i = query[i].next) {
int y = query[i].to;
if (vis[y]) {
ans[query[i].num] = find_set(y);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
init();
memset(vis, 0, sizeof(vis));
int n, m, root;
cin >> n >> m >> root;
for (int i = 1; i < n; i++) {
father[i] = i;
int u, v;
cin >> u >> v;
add(u, v);
add(v, u);
}
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
add_query(x, y, i);
add_query(y, x, i);
}
Tarjan(root);
for (int i = 1; i <= m; i++) {
cout << ans[i] << '\n';
}
return 0;
}
回复
共 1 条回复,欢迎继续交流。
正在加载回复...