#include<bits/stdc++.h>
using namespace std;


const int N = 23;
const int maxn = 1005;
vector<int> g[maxn];
int bin[maxn][N];
bool bio[maxn];
int dist[maxn];
vector<int> rt;

int t,n,q,ciner,m,a,b,c=0,ans=0,r;

void dfs(int x,int y){
    if(bio[x]) return;
    dist[x]= dist[y]+1;
    bin[x][0] = y;
    bio[x] = true;
    for(int i = 0; i < g[x].size(); i++){
        dfs(g[x][i],x);
    }


}


int main(){
    cin >> t;
    for(int _ = 0; _ < t; _++){
        ans=0;
        memset(bin,0,sizeof(bin));
        memset(bio,false,sizeof(bio));
        memset(dist,0,sizeof(dist));
        rt.clear();
        // memset(g,{},sizeof(g));
        
        
        
        cin >> n;
        for(int i = 0; i<n; i++){
            g[i].clear();
        }
        for(int i = 0; i<n; i++){
            
            
            cin >> m;
            for(int j = 0; j<m; j++){
                cin >> ciner;
                ciner--;
                g[i].push_back(ciner);
                rt.push_back(ciner);
                
                
            }
             
        }
        sort(rt.begin(),rt.end());
        for(int i = 0; i<n-1; i++){
            // cout << i << " " << rt[i] << endl;
            if(i!=rt[i]){
                r=i;
                break;
            }
            
        }
        
        cin >> q;
        
        dfs(r,0);
        
        for(int i = 0; i<n; i++){
            for(int j = 1; j<N; j++){
                bin[i][j] = bin[bin[i][j-1]][j-1];
            }
        }
        cout << "Case " << _+1 << ":\n";
        while(q--){
            cin >> a >> b;
            a--; b--;
            c = abs(dist[a]-dist[b]);
            if(dist[a]>dist[b]){
                for(int i = 1; c>=0;i++){
                    if(c&i){
                        a=bin[a][i-1];
                        c-=(2 << i);
                    }
                }
                
            }
            if(dist[a]<dist[b]){
                for(int i = 1; c>=0;i++){
                    if(c&i){
                        b=bin[b][i-1];
                        c-=(2 << i);
                    }
                }
                
            }
            if(a==b){
                cout << a+1 << '\n';
            }
            // cout << dist[a] << " " << dist[b] << endl;
            
            
            else{
                for(int i = N-1; i>=0; i--){
                    if(!(bin[a][i]==bin[b][i])){
                        a=bin[a][i];
                        b=bin[b][i];
                    
                    }
                }
                cout << bin[a][0]+1 << '\n';
            }
            
            

        }

        // for(int i = 0; i<n; i++){
        //     for(int j = 0; j<N; j++){
        //         cout << bin[i][j] << " ";
        //     }
        //     cout << '\n';
        // }



    }

}
