function Main(input) {
    var arr = input.split("\n");
    var n = parseInt(arr[0], 10);
    var nodes = new Array();
    for (i = 0; i < n; i++) {
        nodes.push(new Node(i));
    }
    for (i = 0; i < n; i++) {
        var arr2 = arr[i + 1].split(" ");
        for (j = 0; j < arr2[0]; j++) {
            var c = parseInt(arr2[j + 1], 10);
            nodes[c].setParent(nodes[i]);
        }
    }
    var q = parseInt(arr[n + 1], 10);
    var node = new Node();
    for (i = 0; i < q; i++) {
        var arr2 = arr[n + i + 2].split(" ");
        var u = arr2[0];
        var v = arr2[1];
        console.log(node.findLCA(nodes[u], nodes[v]));
    }
}

function Node(number) {
    this.number = number;
    this.parent = this;
    this.setParent = function(node){
        this.parent = node;
    }
    this.getPath = function(){
        var p = this.parent;
        var path = new Array();
        path.push(p);
        while (p != p.parent) {
            p = p.parent;
            path.push(p);
        }
        return path;
    };
    this.search = function(path) {
        var p = this;
        while(path.indexOf(p) == -1) {
            p = p.parent;
            if(p == p.parent) {
                break;
            }
        }
        return p.number;
    }
    this.findLCA = function(x, y) {
        return x.search(y.getPath());
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));