RMQ版
#define N 10010
struct edge{
int v;
int next;
}e[2*N];
int ecnt;
int head[N];
bool vis[N];
int n;//点数
int R[N];//第一次出现i点下标
int p[N*2];//记录路径点编号
//int dis[N];//与根的距离
int dep[2*N];//深度
int dp[20][2*N];//从j开始长度为2^i路径的最近公共祖先下标
int num;
void init(){
memset(head,-1,sizeof(head));
memset(R,-1,sizeof(R));
memset(vis,0,sizeof(vis));
ecnt=0;
}
void add(int u,int v){
e[ecnt].v = v;
e[ecnt].next = head[u];
head[u] = ecnt++;
e[ecnt].v = u;
e[ecnt].next = head[v];
head[v] = ecnt++;
}
void dfs(int u,int depth){
vis[u] = 1;
p[++num] = u;
dep[num] = depth;
for(int i=head[u];i!=-1;i=e[i].next){
int v = e[i].v;
if(!vis[v]){
dfs(v,depth+1);
p[++num] = u;
dep[num] = depth;
}
}
}
void init_rmq(){
int i,j;
for(i=1;i<=num;i++){
if(R[p[i]] == -1){
R[p[i]] = i;
}
}
for(i=1;i<=num;i++){
dp[0][i] = i;
}
int t = (int)(log(num*1.0)/log(2.0));
for(i=1;i<=t;i++){
for(j=1;j+(1<<(i-1))<=num;j++){
int a = dp[i-1][j],b = dp[i-1][j+(1<<(i-1))];
if(dep[a]<=dep[b]){
dp[i][j] = a;
} else dp[i][j] = b;
}
}
}
int rmq(int u,int v){//返回最近公共祖先的编号
//if(R[u]>=R[v])swap(u,v);
int s = R[u],t = R[v];
if(s>t)swap(s,t);
int k = (int)(log((t-s+1)*1.0)/log(2.0));
int a = dp[k][s],b = dp[k][t-(1<<k)+1];
if(dep[a]<=dep[b])return p[a];
else return p[b];
}
int du[N];
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int i,j;
init();
for(i=0;i<=n;i++)du[i] = 0;
for(i=1;i<n;i++){
int a,b;
scanf("%d%d",&a,&b);
du[b] = 1;
add(a,b);
}
int root=1;
for(i=1;i<=n;i++){
if(!du[i]){
root = i;
break;
}
}
num = 0;
dep[root] = 0;
dfs(root,0);
init_rmq();
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",rmq(a,b));
}
return 0;
}