// Problem: D - 最近公共祖先(LCA)
// Contest: Virtual Judge - 2024 SCUT Winter Training Day 6
// URL: https://vjudge.net/contest/604736#problem/D
// Memory Limit: 524 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
const int N = 5e5 + 10;
int n, m, s;
int Fa[N][32], dep[N];
vector<vector<int>> e(N + 1);
void init(int idx, int ftr) {
Fa[idx][0] = ftr;//2^0=1,即idx的父亲
dep[idx] = dep[ftr] + 1;//深度赋值
for (int i = 1; i < 32; i++)
Fa[idx][i] = Fa[Fa[idx][i - 1]][i - 1];//dp求2倍增祖先
for (int i = 0; i < e[idx].size(); i++) {
if (e[idx][i] == ftr)
continue;
init(e[idx][i], idx);//深搜dfs
}
return;
}
int lca(int a, int b) {
if (a == b)
return a;
if (dep[a] < dep[b])
swap(a, b); // a deeper
int dis = dep[a] - dep[b];
for (int j = 0; dis; j++, dis >>= 1)
if (dis & 1)
a = Fa[a][j];
// 将深度更深的点移动至同一高度
if (a == b)
return a;
// 判断是否同一高度为LCA
for (int j = 31; j >= 0 && a ^ b; j--)
if (Fa[a][j] != Fa[b][j])
a = Fa[a][j], b = Fa[b][j];
// 尽可能逼近LCA,但不跳跃至LCA处
return Fa[a][0];//返回LCA
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m >> s;
int x, y;
for (int i = 1; i < n; i++) {
cin >> x >> y;
e[x].push_back(y);
e[y].push_back(x);//双向加边
}
init(s, 0);
int a, b;
for (int i = 1; i <= m; i++) {
cin >> a >> b;
cout << lca(a, b) << "\n";
}
return 0;
}