0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-23 21:28:48 +00:00

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

https://www.luogu.com.cn/record/94730020
This commit is contained in:
Baoshuo Ren 2022-11-20 09:14:14 +08:00
parent 777fd68b87
commit ef8275fc7a
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A

View File

@ -10,13 +10,14 @@ const char endl = '\n';
const int N = 5e5 + 5;
const int INF = 0x3f3f3f3f;
int n, m, s, dep[N], fa[N][25];
int n, m, s, dep[N], fa[N][std::__lg(N) + 1];
std::vector<int> g[N];
void bfs(int s) {
std::fill_n(dep, N, INF);
std::queue<int> q;
q.emplace(s);
dep[0] = 0;
dep[s] = 1;
@ -31,7 +32,7 @@ void bfs(int s) {
q.emplace(v);
fa[v][0] = u;
for (int k = 1; k <= 19; k++) {
for (int k = 1; k <= std::__lg(n); k++) {
fa[v][k] = fa[fa[v][k - 1]][k - 1];
}
}
@ -42,7 +43,7 @@ void bfs(int s) {
int lca(int x, int y) {
if (dep[x] < dep[y]) std::swap(x, y);
for (int k = 19; k >= 0; k--) {
for (int k = std::__lg(n); k >= 0; k--) {
if (dep[fa[x][k]] >= dep[y]) {
x = fa[x][k];
}
@ -50,7 +51,7 @@ int lca(int x, int y) {
if (x == y) return x;
for (int k = 19; k >= 0; k--) {
for (int k = std::__lg(n); k >= 0; k--) {
if (fa[x][k] != fa[y][k]) {
x = fa[x][k];
y = fa[y][k];