#include <bits/stdc++.h>
using namespace std;
inline long long read()
{
long long x = 0;
int f = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
void write(const long long &x)
{
if (!x)
{
putchar('0');
return;
}
char f[100];
long long tmp = x;
if (tmp < 0)
{
tmp = -tmp;
putchar('-');
}
long long s = 0;
while (tmp > 0)
{
f[s++] = tmp % 10 + '0';
tmp /= 10;
}
while (s > 0)
{
putchar(f[--s]);
}
}
long long totN;
long long totQ;
int head[500090];
int rot;
struct Edge
{
int nxt;
int to;
} edges[1000090];
int cnt_edges;
int lg[1000090];
int fa[500090][35];
int deepth[500090];
void add_edge(int x, int y)
{
++cnt_edges;
edges[cnt_edges].nxt = head[x];
head[x] = cnt_edges;
edges[cnt_edges].to = y;
}
void getLOG()
{
for (int i = 1; i <= totN; i++)
{
lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
}
}
int DFS(int nowX, int fath)
{
fa[nowX][0] = fath;
deepth[nowX] = deepth[fath] + 1;
for (int i = 1; i <= lg[deepth[nowX]]; i++)
{
fa[nowX][i] = fa[fa[nowX][i - 1]][i - 1];
}
for (int i = head[nowX]; i; i = edges[i].nxt)
{
if (edges[i].to == fath)
{
continue;
}
DFS(edges[i].to, nowX);
}
}
int LCA(int x, int y)
{
if (deepth[x] < deepth[y])
{
swap(x, y);
}
while (deepth[x] > deepth[y])
{
x = fa[x][lg[deepth[x] - deepth[y] - 1]];
}
if (x == y)
{
return x;
}
for (int i = lg[deepth[x]] - 1; i >= 0; --i)
{
if (fa[x][i] != fa[y][i])
{
x = fa[x][i];
y = fa[y][i];
}
}
return fa[x][0];
}
int main()
{
totN = read();
totQ = read();
rot = read();
for (int i = 1; i <= totN - 1; i++)
{
int x, y;
x = read();
y = read();
add_edge(x, y);
add_edge(y, x);
}
getLOG();
DFS(rot, 0);
for (int i = 1; i <= totQ; i++)
{
int x, y;
x = read();
y = read();
write(LCA(x, y));
putchar('\n');
}
return 0;
} //LikiBlaze Code
自测数据能过,提交全部TLE