#include<bits/stdc++.h>
using namespace std;

typedef long long int ll;
#define IOS ios_base::sync_with_stdio(0);  cin.tie(0); cout.tie(0);


#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>order_set;
typedef pair<int, int>pr;
#define all(i)     i.begin() , i.end()
#define ft     first
#define sn     second
#define pb push_back

#define en "\n"
#define dbg cout<<"rony\n"

#define MAXN 20010
#define inf 1e6+5
const ll mod = 1e9 + 7;

vector<int>g[MAXN];
int n, q;
int up[MAXN][20];
int dis[MAXN];

void dfs(int nd)
{
    for (auto i : g[nd]) {
        up[i][0] = nd;
        dis[i] = dis[nd] + 1;

        for (int log = 1; log < 20; log++) {
            int ancestor = up[i][log - 1];
            up[i][log] = up[ancestor][log - 1];
        }
        dfs(i);
    }
}

int get_lca(int x, int y)
{
    if (dis[x] < dis[y]) swap(x, y);

    int k = dis[x] - dis[y];
    for (int log = 19; log >= 0; log--)
    {
        if (k & (1 << log)) {
            x = up[x][log];
        }
    }
    if (x == y) return x;

    for (int log = 19; log >= 0; log--)
    {
        if (up[x][log] != up[y][log])
        {
            x = up[x][log];
            y = up[y][log];
        }
    }
    return up[x][0];
}
void solve()
{
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        int m; cin >> m;
        for (int j = 0; j < m; j++) {
            int x;
            cin >> x;
            g[i].pb(x);
        }
    }

    dfs(0);

    int q;
    cin >> q;
    while (q--)
    {
        int x, y;
        cin >> x >> y;

        cout << get_lca(x, y) << en;
    }
}
int main()
{
    IOS;
    ll t;
    t = 1;

    // cin >> t;

    int c = 0;
    while ( t-- )
    {
        // cout<<"Case "<<++c<<": ";
        solve();
    }
    return 0;
}