mirror of
https://git.sb/baoshuo/OI-codes.git
synced 2024-12-25 07:51:58 +00:00
parent
338a79dac9
commit
66a10cd04d
@ -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 (a == b) return a;
|
||||||
if(vis[now]) return now;
|
for (int k = 19; k >= 0; k--) {
|
||||||
else return dfs3(tree[now].father);
|
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;
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user