#include<bits/stdc++.h>
#define PB push_back
#define MP make_pair
#define FI first
#define SE second
#define int long long
using namespace std;
static const int MAX_N = 100000;
static const int inf  = 1ll<<60;
static const int MAX_SEG=1<<17;
typedef pair<int,int> pii;

int N,Q;
vector<int> g[MAX_N+5];
int root;
int depth[MAX_N+5];
int par[21][MAX_N];

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

void fill_table(){
    dfs(root,-1,0);
    for(int i=0;i<20;i++){
        for(int j=0;j<N;j++){
            if(par[i][j]==-1)par[i+1][j]=-1;
            else par[i+1][j]=par[i][par[i][j]];
        }
    }
}

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

signed main(){
    cin>>N;
    for(int i=0;i<N;++i){
        int k;
        cin>>k;
        for(int j=0;j<k;++j){
            int c;
            cin>>c;
            g[i].PB(c);
        }
    }
    fill_table();
    cin>>Q;
    while(Q--){
        int u,v;
        cin>>u>>v;
        cout<<LCA(u,v)<<endl;
    }
}