#include<bits/stdc++.h>
using namespace std;
int n, q, l;
int u[100010], v[100010];
vector<int> C[100010];
int depth[100010], par[20][100010];

void dfs(int v, int p, int d){
    par[0][v] = p;
    depth[v] = d;
    for(auto u : C[v]){
        dfs(u, v, d + 1);
    }
}

void build(){
    dfs(0, -1, 0);
    for(int k = 0; k <= l; k++){
        for(int i = 0; i < n; i++){
            if(par[k][i] == -1) par[k + 1][i] = -1;
            else par[k + 1][i] = par[k][par[k][i]];
        }
    }
}

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

void solve(){
    build();
    cin >> q;
    for(int i = 0; i < q; i++){
        int u, v;
        cin >> u >> v;
        cout << lca(u, v) << endl;
    }
}

void init(){
    cin >> n;
    for(int i = 0; i < n; i++){
        int k;
        cin >> k;
        for(int j = 0; j < k; j++){
            int chi;
            cin >> chi;
            C[i].push_back(chi);
        }
    }
    while((1 << l) < n) l++;
}

int main(){
    init();
    solve();
    return 0;
}
