/*
Copyright 2013 Jakub "Cubix651" Cisło
Solving Lowest Common Ancestor (LCA) problem offline.
Tarjan's algorithm. Complexity: O(alpha(n) * n)
*/
#include <cstdio>
#include <vector>
using namespace std;
const int MAX = 1000000;
vector<int> graph[MAX], query[MAX], answer[MAX];
int n, q, x, y, rep[MAX], rank[MAX], anc[MAX];
short int visited[MAX]; //0 - not visited, 1 - visited 2 - processed
int Find(int a)
{
if(rep[a] != a)
rep[a] = Find(rep[a]);
return rep[a];
}
void Union(int a, int b)
{
a = Find(a);
b = Find(b);
if(a == b) return;
if(rank[a] < rank[b])
rep[a] = b;
else if(rank[b] < rank[a])
rep[b] = a;
else
{
rep[a] = b;
++rank[b];
}
}
void MakeSets(int m)
{
while(m--)
{
rep[m] = m;
rank[m] = 0;
}
}
void dfs(int v)
{
visited[v] = 1;
anc[v] = v;
for(int i = 0; i < graph[v].size(); ++i)
{
if(visited[graph[v][i]] == 0)
{
dfs(graph[v][i]);
Union(v, graph[v][i]);
anc[Find(v)] = v;
}
}
visited[v] = 2;
for(int i = 0; i < query[v].size(); ++i)
{
if(visited[query[v][i]] == 2)
answer[v][i] = anc[Find(query[v][i])];
}
}
void LCA(int n, int root)
{
MakeSets(n);
for(int i = 1; i <= n; ++i)
answer[i].resize(query[i].size());
dfs(root);
}
int main()
{
scanf("%d", &n);
for(int i = 1; i < n; ++i)
{
scanf("%d%d", &x, &y);
graph[x].push_back(y);
graph[y].push_back(x);
}
scanf("%d", &q);
while(q--)
{
scanf("%d%d", &x, &y);
query[x].push_back(y);
if(x!=y)
query[y].push_back(x);
}
LCA(n, 1);
for(int i = 1; i <= n; ++i)
{
for(int j = 0; j < query[i].size(); ++j)
{
if(answer[i][j] != 0)
printf("LCA(%d, %d) = %d\n", i, query[i][j], answer[i][j]);
}
}
return 0;
}
LyogCiAgIENvcHlyaWdodCAyMDEzIEpha3ViICJDdWJpeDY1MSIgQ2lzxYJvCiAgIFNvbHZpbmcgTG93ZXN0IENvbW1vbiBBbmNlc3R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