#include <bits/stdc++.h>
#define ll long long
#define INF 1000000005
#define MOD 1000000007
#define EPS 1e-10
#define rep(i,n) for(int i=0;i<(int)n;++i)
#define each(a, b) for(auto (a): (b))
#define all(v) (v).begin(),(v).end()
#define fi first
#define se second
#define pb push_back
#define show(x) cout <<#x<<" = "<<(x)<<endl
#define spair(p) cout <<#p<<": "<<p.fi<<" "<<p.se<<endl
#define svec(v) cout<<#v<<":";rep(kbrni,v.size())cout<<" "<<v[kbrni];cout<<endl
#define sset(s) cout<<#s<<":";each(kbrni,s)cout <<" "<<kbrni;cout<<endl

using namespace std;

typedef pair<int,int>P;

const int MAX_N = 100005;
const int LOG_N = 17;

vector<int> G[MAX_N];

int par[LOG_N][MAX_N];
int depth[MAX_N];

void dfs(int u,int p,int d)
{
    par[0][u] = p;
    depth[u] = d;
    rep(i,G[u].size()){
        if(G[u][i] != p){
            dfs(G[u][i],u,d+1);
        }
    }
}

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

int main()
{
    int n;
    cin >> n;
    rep(i,n){
        int m;
        scanf("%d",&m);
        rep(j,m){
            int x;
            scanf("%d",&x);
            G[i].pb(x);
        }
    }
    dfs(0,-1,0);
    rep(i,LOG_N-1){
        rep(j,n){
            if(par[i][j] < 0){
                par[i+1][j] = -1;
            }else{
                par[i+1][j] = par[i][par[i][j]];
            }
        }
    }
    int q;
    cin >> q;
    rep(i,q){
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",lca(x,y));
    }
    return 0;
}