#include<bits/stdc++.h>
#define range(i,a,b) for(int i = (a); i < (b); i++)
#define rep(i,b) for(int i = 0; i < (b); i++)
#define all(a) (a).begin(), (a).end()
#define show(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
const int INF = 2000000000;
using namespace std;

const int MAX_V = 100000;
const int MAX_LOG_V = 17;

vector<int> g[MAX_V]; //??°???????????£??\?????????
int root;

int parent[MAX_LOG_V][MAX_V];
int depth[MAX_V];

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

void init(int v){
    dfs(root, -1, 0);
    rep(i,MAX_LOG_V - 1){
        rep(j,v){
            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);
    rep(i,MAX_LOG_V){
        if((depth[v] - depth[u]) >> i & 1){
            v = parent[i][v];
        }
    }
    if(u == v) return u;

    //????????¢?´¢
    for(int i = MAX_LOG_V - 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;
    cin >> n;
    rep(i,n){
        int k;
        cin >> k;
        rep(j,k){
            int v;
            cin >> v;
            g[i].emplace_back(v);
            g[v].emplace_back(i);
        }
    }

    init(n);

    int q;
    cin >> q;
    rep(i,q){
        int u, v;
        cin >> u >> v;
        cout << lca(u,v) << endl;
    }
}