社区讨论
树剖模板炸了
P3379【模板】最近公共祖先(LCA)参与者 4已保存回复 6
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 6 条
- 当前快照
- 1 份
- 快照标识符
- @mhizg23q
- 此快照首次捕获于
- 2025/11/03 18:13 4 个月前
- 此快照最后确认于
- 2025/11/03 18:13 4 个月前
复习树剖发现树剖不会了
CPP#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int n, m, s, dep[N], siz[N], fa[N], son[N], top[N];
vector <int> p[N];
void dfs1(int u) {
siz[u] = 1;
for (auto to : p[u]) {
if (to == fa[u]) continue ;
fa[to] = u;
dep[to] = dep[u] + 1;
dfs1(to);
siz[u] += siz[to];
if (siz[son[u]] < siz[to]) son[u] = to;
}
}
void dfs2(int u) {
for (auto to : p[u]) {
if (to == fa[u]) continue ;
top[to] = (son[u] == to) ? top[u] : to;
dfs2(to);
}
}
void read(int &x) {
x = 0;
char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
}
int main() {
read(n), read(m), read(s);
for (int i = 1, u, v; i < n; ++i) {
read(u), read(v);
p[u].push_back(v);
p[v].push_back(u);
}
dfs1(s);
top[s] = s, fa[s] = s;
dfs2(s);
while (m--) {
int x, y;
read(x), read(y);
while (top[x] != top[y])
(dep[x] > dep[y]) ? x = fa[top[x]] : y = fa[top[y]];
printf("%d\n", (dep[x] < dep[y]) ? x : y);
}
return 0;
}
回复
共 6 条回复,欢迎继续交流。
正在加载回复...