2022-10-28 12:46:59 +00:00
|
|
|
#include <iostream>
|
|
|
|
#include <algorithm>
|
|
|
|
#include <queue>
|
|
|
|
#include <vector>
|
2021-10-22 03:47:35 +00:00
|
|
|
|
2022-10-28 12:46:59 +00:00
|
|
|
using std::cin;
|
|
|
|
using std::cout;
|
|
|
|
const char endl = '\n';
|
2021-10-22 03:47:35 +00:00
|
|
|
|
2022-10-28 12:46:59 +00:00
|
|
|
const int N = 5e5 + 5;
|
|
|
|
const int INF = 0x3f3f3f3f;
|
2021-10-22 03:47:35 +00:00
|
|
|
|
2022-10-28 12:46:59 +00:00
|
|
|
int n, m, s, dep[N], fa[N][25];
|
|
|
|
std::vector<int> g[N];
|
|
|
|
|
|
|
|
void bfs(int s) {
|
|
|
|
std::fill_n(dep, N, INF);
|
|
|
|
|
|
|
|
std::queue<int> q;
|
|
|
|
q.emplace(s);
|
2021-10-22 03:47:35 +00:00
|
|
|
dep[0] = 0;
|
2022-10-28 12:46:59 +00:00
|
|
|
dep[s] = 1;
|
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
while (!q.empty()) {
|
2022-10-28 12:46:59 +00:00
|
|
|
int u = q.front();
|
2021-10-22 03:47:35 +00:00
|
|
|
q.pop();
|
2022-10-28 12:46:59 +00:00
|
|
|
|
|
|
|
for (int v : g[u]) {
|
|
|
|
if (dep[v] > dep[u] + 1) {
|
|
|
|
dep[v] = dep[u] + 1;
|
|
|
|
q.emplace(v);
|
|
|
|
fa[v][0] = u;
|
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
for (int k = 1; k <= 19; k++) {
|
2022-10-28 12:46:59 +00:00
|
|
|
fa[v][k] = fa[fa[v][k - 1]][k - 1];
|
2021-10-22 03:47:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-28 12:46:59 +00:00
|
|
|
int lca(int x, int y) {
|
|
|
|
if (dep[x] < dep[y]) std::swap(x, y);
|
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
for (int k = 19; k >= 0; k--) {
|
2022-10-28 12:46:59 +00:00
|
|
|
if (dep[fa[x][k]] >= dep[y]) {
|
|
|
|
x = fa[x][k];
|
2021-10-22 03:47:35 +00:00
|
|
|
}
|
|
|
|
}
|
2022-10-28 12:46:59 +00:00
|
|
|
|
|
|
|
if (x == y) return x;
|
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
for (int k = 19; k >= 0; k--) {
|
2022-10-28 12:46:59 +00:00
|
|
|
if (fa[x][k] != fa[y][k]) {
|
|
|
|
x = fa[x][k];
|
|
|
|
y = fa[y][k];
|
2021-10-22 03:47:35 +00:00
|
|
|
}
|
|
|
|
}
|
2022-10-28 12:46:59 +00:00
|
|
|
|
|
|
|
return fa[x][0];
|
2021-10-22 03:47:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
2022-10-28 12:46:59 +00:00
|
|
|
std::ios::sync_with_stdio(false);
|
|
|
|
cin.tie(nullptr);
|
|
|
|
|
|
|
|
cin >> n >> m >> s;
|
|
|
|
|
|
|
|
for (int i = 1, u, v; i < n; i++) {
|
|
|
|
cin >> u >> v;
|
|
|
|
|
|
|
|
g[u].emplace_back(v);
|
|
|
|
g[v].emplace_back(u);
|
2021-10-22 03:47:35 +00:00
|
|
|
}
|
2022-10-28 12:46:59 +00:00
|
|
|
|
|
|
|
bfs(s);
|
|
|
|
|
|
|
|
while (m--) {
|
|
|
|
int a, b;
|
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
cin >> a >> b;
|
2022-10-28 12:46:59 +00:00
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
cout << lca(a, b) << endl;
|
|
|
|
}
|
2022-10-28 12:46:59 +00:00
|
|
|
|
2021-10-22 03:47:35 +00:00
|
|
|
return 0;
|
|
|
|
}
|