1 #include <algorithm>
2 #include <cstdio>
3 #include <vector>
4
5 using namespace std;
6
7 const int N(10005);
8 vector<int>vec[N];
9 int n,q,x,y;
10 int size[N],deep[N],top[N],dad[N];
11
12 void DFS(int x)
13 {
14 size[x]=1; deep[x]=deep[dad[x]]+1;
15 for(int i=0;i<vec[x].size();i++)
16 if(vec[x][i]!=dad[x])
17 {
18 dad[vec[x][i]]=x;
19 DFS(vec[x][i]);
20 size[x]+=size[vec[x][i]];
21 }
22 }
23
24 void DFS_(int x)
25 {
26 int t=0; if(!top[x]) top[x]=x;
27 for(int i=0;i<vec[x].size();i++)
28 if(vec[x][i]!=dad[x]&&size[t]<size[vec[x][i]]) t=vec[x][i];
29 if(t) top[t]=top[x], DFS_(t);
30 for(int i=0;i<vec[x].size();i++)
31 if(vec[x][i]!=dad[x]&&t!=vec[x][i]) DFS_(vec[x][i]);
32 }
33
34 int LCA(int x,int y)
35 {
36 while(top[x]!=top[y])
37 {
38 if(deep[top[x]]<deep[top[y]]) swap(x,y);
39 x=dad[top[x]];
40 }
41 if(deep[x]>deep[y]) swap(x,y);
42 return x;
43 }
44
45 int main()
46 {
47 scanf("%d",&n);
48 for(int i=1;i<n;i++)
49 {
50 scanf("%d%d",&x,&y);
51 vec[x].push_back(y);
52 vec[y].push_back(x);
53 }
54 DFS(1); DFS_(1);
55 scanf("%d",&q);
56 for(;q;q--)
57 {
58 scanf("%d%d",&x,&y);
59 printf("%d
",LCA(x,y));
60 }
61 return 0;
62 }