#include <bits/stdc++.h>
#define ll long long
#define V vector<long long>
#define VV vector<vector<long long>>
#define rep(i,n) for(ll (i)=0;(i)<(n);++(i))
using namespace std;

template<typename T>
struct lowest_common_ancestor{
    T n,logn;
    vector<T> depth;
    vector<vector<T>> g,next;
    lowest_common_ancestor(vector<vector<T>> const& g):g(g),n(g.size()),logn(floor(log2(g.size()))),depth(g.size()){
        next.assign(n,vector<T>(logn+1));
        dfs(0,-1,0);
        for(T k=0;k<logn;++k){
            for(T i=0;i<n;++i){
                if(next[i][k]==-1)next[i][k+1]=-1;
                else next[i][k+1]=next[next[i][k]][k];
            }
        }
    }
    void dfs(T now,T par,T dep){
        depth[now]=dep;
        next[now][0]=par;
        for(T i=0;i<g[now].size();++i){
            if(g[now][i]!=par){
                dfs(g[now][i],now,dep+1);
            }
        }
    }
    T query(T a,T b){
        if(depth[a]<depth[b])swap(a,b);
            for(T k=logn;k>=0;--k){
                if((1<<k) & depth[a]-depth[b]){
                    a=next[a][k];
                }
            }
        if(a==b)return a;
            for(T k=logn;k>=0;--k){
                if(next[a][k] != next[b][k]){
                    a=next[a][k];
                    b=next[b][k];
                }
            }
        return next[a][0];
    }
    T distance(T a,T b){
        return depth[a]+depth[b]-2*depth[query(a,b)];
    }
};

int main(){
    ll n;
    cin>>n;
    VV g(n,vector<ll>());
    rep(i,n){
        ll k;
        cin>>k;
        rep(j,k){
            ll c;
            cin>>c;
            g[i].push_back(c);
            g[c].push_back(i);
        }
    }
    lowest_common_ancestor<ll> lca(g);
    ll q;
    cin>>q;
    rep(i,q){
        ll u,v;
        cin>>u>>v;
        cout<<lca.query(u, v)<<endl;
    }
}

