From 996fcb26c4dca13cf23d5bcc1fad6077c9d6ded2 Mon Sep 17 00:00:00 2001 From: Ren Baoshuo Date: Wed, 30 Jun 2021 10:25:10 +0800 Subject: [PATCH] =?UTF-8?q?#109.=20=E3=80=90=E6=A8=A1=E6=9D=BF=E3=80=91?= =?UTF-8?q?=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88=EF=BC=88?= =?UTF-8?q?LCA=EF=BC=89=20[80'=20Code]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://sjzezoj.com/submission/12017 --- S2OJ/109/109.cpp | 56 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 S2OJ/109/109.cpp diff --git a/S2OJ/109/109.cpp b/S2OJ/109/109.cpp new file mode 100644 index 00000000..8adf0148 --- /dev/null +++ b/S2OJ/109/109.cpp @@ -0,0 +1,56 @@ +#include + +using namespace std; + +int n, m, s, x, y; + +struct node { + int depth, father; + vector next; +} tree[500005]; +bool vis[500005]; + +void dfs(int depth, int root, int father) { + tree[root].father = father; + for (int i = 0; i < tree[root].next.size(); i++) { + if (tree[root].next[i] != father) { + tree[tree[root].next[i]].depth = depth + 1; + tree[tree[root].next[i]].father = root; + dfs(depth + 1, tree[root].next[i], root); + } + } + return; +} + +void dfs2(int now) { + vis[now] = true; + if(now == s) return; + else dfs2(tree[now].father); +} + +int dfs3(int now) { + if(vis[now]) return now; + else return dfs3(tree[now].father); +} + +int main() { + scanf("%d%d%d", &n, &m, &s); + for (int i = 1; i < n; i++) { + scanf("%d%d", &x, &y); + tree[x].next.push_back(y); + tree[y].next.push_back(x); + } + dfs(1, s, s); + for(int i = 0 ; i < m ; i++) { + scanf("%d%d", &x, &y); + memset(vis, 0x00, sizeof(vis)); + if(tree[x].depth > tree[y].depth) { + dfs2(x); + printf("%d\n", dfs3(y)); + } else { + dfs2(y); + printf("%d\n", dfs3(x)); + } + } + return 0; +}