0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-12-24 18:52:02 +00:00

#109. 【模板】最近公共祖先(LCA)

https://sjzezoj.com/submission/41223
This commit is contained in:
Baoshuo Ren 2021-10-22 15:24:37 +08:00 committed by Baoshuo Ren
parent 338a79dac9
commit 66a10cd04d
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

View File

@ -1,56 +1,62 @@
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h> #include <bits/stdc++.h>
using namespace std; using namespace std;
int n, m, s, x, y; int n, m, s, root, a, b, dep[500005], fa[500005][20];
vector<int> tr[500005];
struct node { void bfs(int root) {
int depth, father; memset(dep, 0x3f, sizeof(dep));
vector<int> next; dep[0] = 0;
} tree[500005]; dep[root] = 1;
bool vis[500005]; queue<int> q;
q.push(root);
void dfs(int depth, int root, int father) { while (!q.empty()) {
tree[root].father = father; int t = q.front();
for (int i = 0; i < tree[root].next.size(); i++) { q.pop();
if (tree[root].next[i] != father) { for (int i : tr[t]) {
tree[tree[root].next[i]].depth = depth + 1; if (dep[i] > dep[t] + 1) {
tree[tree[root].next[i]].father = root; dep[i] = dep[t] + 1;
dfs(depth + 1, tree[root].next[i], root); q.push(i);
fa[i][0] = t;
for (int k = 1; k <= 19; k++) {
fa[i][k] = fa[fa[i][k - 1]][k - 1];
}
}
} }
} }
return;
} }
void dfs2(int now) { int lca(int a, int b) {
vis[now] = true; if (dep[a] < dep[b]) swap(a, b);
if(now == s) return; for (int k = 19; k >= 0; k--) {
else dfs2(tree[now].father); if (dep[fa[a][k]] >= dep[b]) {
} a = fa[a][k];
}
int dfs3(int now) { }
if(vis[now]) return now; if (a == b) return a;
else return dfs3(tree[now].father); for (int k = 19; k >= 0; k--) {
if (fa[a][k] != fa[b][k]) {
a = fa[a][k];
b = fa[b][k];
}
}
return fa[a][0];
} }
int main() { int main() {
scanf("%d%d%d", &n, &m, &s); scanf("%d%d%d", &n, &m, &root);
for (int i = 1; i < n; i++) { for (int i = 1; i < n; i++) {
scanf("%d%d", &x, &y); scanf("%d%d", &a, &b);
tree[x].next.push_back(y); tr[a].push_back(b);
tree[y].next.push_back(x); tr[b].push_back(a);
} }
dfs(1, s, s); bfs(root);
for(int i = 0 ; i < m ; i++) { for (int i = 0; i < m; i++) {
scanf("%d%d", &x, &y); scanf("%d%d", &a, &b);
memset(vis, 0x00, sizeof(vis)); printf("%d\n", lca(a, b));
if(tree[x].depth > tree[y].depth) {
dfs2(x);
printf("%d\n", dfs3(y));
} else {
dfs2(y);
printf("%d\n", dfs3(x));
}
} }
return 0; return 0;
} }