#include<bits/stdc++.h>

using namespace std;
#define MAX 100000
#define MAX_PARENT 100

vector<int>G[MAX];
int depth[MAX];
int parent[MAX_PARENT][MAX];
int root = 0;

void dfs(int v,int p,int d){
    parent[0][v] = p;
    depth[v] = d;
    for(int i = 0;i < G[v].size();++i){
        if(G[v][i] != p)
            dfs(G[v][i],v,d + 1);
    }
}

void init(int v){
    dfs(root,-1,0);
    for(int i = 0;i + 1 < MAX_PARENT;++i){
        for(int j = 0;j < v;++j){
            if(parent[i][j] < 0){
                parent[i + 1][j]= -1;  
            } 
            else{
                parent[i + 1][j] = parent[i][parent[i][j]];  
            } 
        }
    }
}

int lca(int u,int v){
    if(depth[u] > depth[v]){
        swap(u,v);   
    }
    
    for(int i = 0;i < MAX_PARENT;++i){
        if((depth[v] - depth[u]) >> i & 1){
            v = parent[i][v];
        }
    }
    if(u == v){
        return u;
    }
    
    for(int i = MAX_PARENT -1;i >= 0;--i){
        if(parent[i][u] != parent[i][v]){
            u = parent[i][u];
            v = parent[i][v];
        }
    }
    return parent[0][u];
}

int main(){
    int n,p,t;
    cin>>n;
    for(int i = 0;i < n;++i){
        cin >> p;
        for(int j = 0;j < p;++j){
            cin >> t;
            G[i].push_back(t);
        }
    }
    init(n);
    cin >> n;
    for(int i = 0;i < n;++i){
        cin >> p >> t;
        cout << lca(p,t) << endl;
    }
}
