#include<bits/stdc++.h>
using namespace std;
using UL = unsigned int;
using ULL = unsigned long long;
using LL = long long;
#define rep(i, n) for(UL i = 0; i < (n); i++)

struct Problem {

    UL P[100000][17];
    UL D[100000];
    vector<UL> E[100000];

    UL UP(UL u, UL d) {
        for (UL i = 16; i != -1; i--) if (d & (1 << i)) u = P[u][i];
        return u;
    }

    UL LCS(UL u, UL v) {
        if (D[u] > D[v]) u = UP(u, D[u] - D[v]);
        else if (D[u] < D[v]) v = UP(v, D[v] - D[u]);
        for (UL i = 16; i != -1; i--) {
            if (P[u][i] != P[v][i]) { u = P[u][i]; v = P[v][i]; }
        }
        if (u == v) return u;
        return P[u][0];
    }

    void Solve() {
        UL N; scanf("%d", &N);
        P[0][0] = 0;
        rep(u, N) {
            UL K; scanf("%d", &K);
            while (K--) {
                UL v; scanf("%d", &v);
                E[u].push_back(v); P[v][0] = u;
            }
        }
        {
            vector<UL> Q; Q.push_back(0); D[0] = 0;
            while (Q.size()) {
                UL p = Q.back(); Q.pop_back();
                for (UL e : E[p]) { D[e] = D[p] + 1; Q.push_back(e); }
            }
        }
        rep(i, 16) rep(v, N) P[v][i + 1] = P[P[v][i]][i];
        UL Q; scanf("%d", &Q);
        while (Q--) {
            UL u, v; scanf("%d%d", &u, &v);
            printf("%d\n", LCS(u, v));
        }
    }
};
int main() {
    unique_ptr<Problem> p(new Problem());
    //cout << fixed << setprecision(10);
    p->Solve();
    return 0;
}


