#include <bits/stdc++.h>
using namespace std;

struct Edge {
    int from, to;
    int64_t cost;
    Edge(int _to) : from(-1), to(_to), cost(-1) {}
    Edge(int _to, int64_t _cost) : from(-1), to(_to), cost(_cost) {}
};

class LCA {
public:
    const int K = 18;
    vector<vector<int>> par;
    vector<int> depth;
    LCA(const vector<vector<Edge>> &G) {
        par.assign(K + 1, vector<int>(G.size()));
        depth.resize(G.size());
        dfs(G, 0, -1, 0);
        for(int k = 0; k < K; ++k) {
            for(int i = 0; i < G.size(); ++i) {
                if(par[k][i] == -1) par[k + 1][i] = -1;
                else par[k + 1][i] = par[k][par[k][i]];
            }
        }
    }

    void dfs(const vector<vector<Edge>> &G, int u, int v, int d) {
        par[0][u] = v;
        depth[u] = d;
        for(auto &e : G[u]) {
            if(e.to != v) dfs(G, e.to, u, d + 1);
        }
    }

    int operator()(int u, int v) {
        if(depth[u] > depth[v]) swap(u, v);
        for(int i = K - 1; i >= 0; --i) {
            if((depth[v] - depth[u]) & (1 << i)) v = par[i][v];
        }
        if(u == v) return u;
        for(int i = K - 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;
    vector<vector<Edge>> G(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].emplace_back(c);
        }
    }
    LCA lca(G);
    int Q; cin >> Q;
    while(Q--) {
        int u, v;
        cin >> u >> v;
        cout << lca(u, v) << endl;
    }
    return 0;
}

