#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<vector>
#include<functional>
#include<cmath>
#include<map>
#include<stack>
#include<set>
#include<numeric>
#include<limits>
#include<iterator>

#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define rep(i,n) for(int i=0; i<n; i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef pair<ll, char> plc;

#define MAX_N 100100
#define MAX_LOG_N 20
int N, root;
vector<int> g[MAX_N];
int depth[MAX_N];
int par[MAX_N][MAX_LOG_N];

void dfs(int v, int p, int d)
{
	par[v][0] = p;
	depth[v] = d;
	for (int i = 0; i < g[v].size(); i++)
	{
		if (g[v][i] == p)continue;
		dfs(g[v][i], v, d + 1);
	}
}

void fill_table()
{
	for (int i = 0; i < 19; i++)
	{
		for (int j = 0; j < N; j++)
		{
			if (par[j][i] == -1)par[j][i + 1] = -1;
			else par[j][i + 1] = par[par[j][i]][i];
		}
	}
}

int lca(int u, int v)
{
	if (depth[u] > depth[v])swap(u, v);
	for (int i = 19; i >= 0; i--)
	{
		if (((depth[v] - depth[u]) >> i) & 1)v = par[v][i];
	}
	if (u == v)return u;
	for (int i = 19; i >= 0; i--)
	{
		if (par[u][i] != par[v][i])
		{
			u = par[u][i];
			v = par[v][i];
		}
	}
	return par[u][0];
}

int main()
{
	int q;
	cin >> N;

	rep(i, N) {
		int k;
		cin >> k;
		rep(j, k) {
			int c;
			cin >> c;
			g[i].push_back(c);
		}
	}
	root = 0;
	dfs(root, -1, 0);
	fill_table();

	cin >> q;
	rep(i, q) {
		int u, v;
		cin >> u >> v;
		cout << lca(u, v) << endl;
	}
	return 0;
}