#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
#define INF (int)1e9
int n, father[10005], depth[10005], dp[10005][20];
vector<int> child[10005];
void dfs(int cur, int par, int dep){
father[cur] = par;
depth[cur] = dep;
for(int i = 0; i < child[cur].size(); i++){
int next = child[cur][i];
dfs(next, cur, dep+1);
}
}
void precompute(){
for(int i = 0; i < 10005; i++){
for(int j = 0; j < 20; j++){
dp[i][j] = 1;
}
}
for(int i = 1; i <= n; i++){
dp[i][0] = father[i];
}
for(int p = 1; p <= 15; p++){
for(int cur = 1; cur <= n; cur++){
dp[cur][p] = dp[dp[cur][p-1]][p-1];
}
}
}
int lca(int a, int b){
if(depth[a] > depth[b]){
swap(a, b);
}
int dif = depth[b] - depth[a];
for(int p = 15; p >= 0; p--){
if( (1 << p) <= dif ){
b = dp[b][p];
dif -= (1 << p);
}
}
if(a == b){
return a;
}
for(int p = 15; p >= 0; p--){
if( dp[b][p] != dp[a][p] ){
a = dp[a][p];
b = dp[b][p];
}
}
return father[a];
}
int main(){
int t;
cin >> t;
for(int test = 1; test <= t; test++){
cout << "Case " << t << ":" << endl;
cin >> n;
int m, temp;
for(int i = 1; i <= n; i++){
cin >> m;
for(int j = 1; j <= m; j++){
cin >> temp;
child[i].push_back(temp);
}
}
dfs(1, 1, 0);
precompute();
int q, a, b;
cin >> q;
for(int i = 1; i <= q; i++){
cin >> a >> b;
cout << lca(a, b) << endl;
}
for(int i = 1; i <= n; i++){
child[i].clear();
father[i] = 0;
depth[i] = 0;
}
}
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnR5cGVkZWYgbG9uZyBsb25nIGxsOwp0eXBlZGVmIHZlY3RvcjxpbnQ+IHZpOwp0eXBlZGVmIHZlY3RvcjxsbD4gdmw7CgojZGVmaW5lIElORiAoaW50KTFlOQoKaW50IG4sIGZhdGhlclsxMDAwNV0sIGRlcHRoWzEwMDA1X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