#include <bits/stdc++.h>
#define pb push_back
using namespace std;
const int maxn=100005;
const int logn=20;

int n,q,l;
int dep[maxn];
int up[maxn][logn];
vector<int>G[maxn];

void dfs(int u,int p) {
    dep[u]=dep[p]+1;
    up[u][0]=p;
    for (int i=0;i<l;i++) up[u][i+1]=up[up[u][i]][i];
    for (int v:G[u])
        if (v!=p) dfs(v,u);
}

int lca(int u,int v) {
    if (dep[u]<dep[v]) swap(u,v);
    for (int i=l;i>=0;i--) {
        if (dep[up[u][i]]>=dep[v]) u=up[u][i];
        if (u==v) return u;
    }
    for (int i=l;i>=0;i--)
        if (up[u][i]!=up[v][i]) {
            u=up[u][i];
            v=up[v][i];
        }
    return up[u][0];
}

int main() {
    cin>>n;
    for (int i=0;i<n;i++) {
        int m; cin>>m;
        for (int j=0;j<m;j++) {
            int v; cin>>v;
            G[i].pb(v);
        }
    }
    while ((1<<l)<=n) ++l;
    dfs(0,0);
    cin>>q;
    for (int i=0;i<q;i++) {
        int u,v; cin>>u>>v;
        cout<<lca(u,v)<<'\n';
    }
}
