import std.algorithm;
import std.array;
import std.ascii;
import std.container;
import std.conv;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.typecons;
import core.bitop;

void log(A...)(A arg) {
    stderr.writeln(arg);
}
int size(T)(in T s) {
    return cast(int)s.length;
}

class Tree {
    int N; // Graph(Tree)???????????°
    int[][] G; // Graph(Tree)?????£??\???????????¨???
    int[] D; // ????????????root??????????????¢
    int LOG_N; // log2(N)?????????
    int[][] P; // P[k][v] : ??????v???2^k?????????????\?
    void dfs(int prev, int index, int d) {
        P[0][index] = prev;
        D[index] = d;
        for (int i = 0; i < G[index].size; i++) {
            int next = G[index][i];
            if (next == prev) continue;
            dfs(index, next, d + 1);
        }
    }
    this(int[][] G) {
        this.N = G.size;
        this.G = G;
        this.LOG_N = bsr(N) + 1;
        this.P = new int[][](LOG_N, N);
        this.D = new int[N]; D[] = -1;
        dfs(-1, 0, 0);
        for (int k = 0; k < LOG_N - 1; k++) {
            for (int v = 0; v < N; v++) {
                if (P[k][v] < 0) P[k + 1][v] = -1;
                else P[k + 1][v] = P[k][ P[k][v] ];
            }
        }
    }
    // ??????v???n?????????????????????
    int nth_parent(int v, int n) {
        for (int k = 0; k < LOG_N; k++)
            if (n & (1 << k)) v = P[k][v];
        return v;
    }
    // 2??????u??¨v???LCA?????????
    int lca(int u, int v) {
        if (D[u] > D[v]) swap(u, v);
        v = nth_parent(v, D[v] - D[u]);
        if (u == v) return u;
        for (int k = LOG_N - 1; k >= 0; k--) {
            if (P[k][u] != P[k][v]) {
                u = P[k][u];
                v = P[k][v];
            }
        }
        return P[0][u];
    }
    // 2??????u??¨v????????¢?????????
    int dist(int u, int v) {
        int root = lca(u, v);
        return (D[u] - D[root]) + (D[v] - D[root]);
    }
}

void main() {
    int N = readln.chomp.to!int;
    auto G = new int[][N];
    for (int i = 0; i < N; i++) {
        int k; scanf("%d ", &k);
        for (int j = 0; j < k; j++) {
            int c; scanf("%d", &c);
            G[i] ~= c;
        }
    }
    auto t = new Tree(G);
    int Q; scanf("%d", &Q);
    for (int q = 0; q < Q; q++) {
        int u, v; scanf("%d %d", &u, &v);
        writeln(t.lca(u, v));
    }
}