import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, std.bitmanip;


void main() {
    auto n = readln.chomp.to!int;
    auto g = new int[][](n);
    foreach (i; 0..n) {
        auto s = readln.split.map!(to!int).array;
        auto k = s.front;
        foreach (j; 1..k+1) {
            g[i] ~= s[j];
            g[s[j]] ~= i;
        }
    }

    auto lca = new LowestCommonAncestor(g, 0);

    auto q = readln.chomp.to!int;
    while (q--) {
        auto s = readln.split.map!(to!int);
        auto x = s[0];
        auto y = s[1];
        writeln(lca.lca(x, y));
    }
}


class LowestCommonAncestor {
    import std.algorithm : swap;
    import std.conv : to;
    import std.typecons : Tuple, tuple;
    import core.bitop : bsr;

    int n, root, lgn;
    int[][] graph;
    int[] depth;
    int[][] dp;

    this(const int[][] graph, int root) {
        n = graph.length.to!int;
        this.root = root;
        this.graph = new int[][](n);
        foreach (i; 0..n) this.graph[i] = graph[i].dup;

        lgn = bsr(n) + 3;
        depth = new int[](n);
        dp = new int[][](lgn, n);

        construct;
    }

    int lca(int a, int b) {
        if (depth[a] < depth[b]) swap(a, b);

        int diff = depth[a] - depth[b];
        foreach_reverse (i; 0..lgn) if (diff & (1<<i)) a = dp[i][a];

        if (a == b) return a;

        int K = lgn;
        while (dp[0][a] != dp[0][b]) {
            foreach_reverse (k; 0..lgn) {
                if (dp[k][a] != dp[k][b]) {
                    a = dp[k][a];
                    b = dp[k][b];
                    K = k;
                }
            }
        }

        return dp[0][a];
    }

    private void construct() {
        auto stack = new Tuple!(int, int, int)[](n+10);
        int sp = 0;
        stack[0] = tuple(root, -1, 0);
        while (sp >= 0) {
            auto u = stack[sp][0];
            auto p = stack[sp][1];
            auto d = stack[sp][2];
            sp -= 1;
            dp[0][u] = p;
            depth[u] = d;
            foreach (v; graph[u]) if (v != p) stack[++sp] = tuple(v, u, d+1);
        }

        foreach (k; 0..lgn-1)
            foreach (i; 0..n)
                dp[k+1][i] = (dp[k][i] == -1) ? -1 : dp[k][dp[k][i]];
    }
}

