#include <bits/stdc++.h>
using namespace std;
using graph = vector<vector<int>>;

class LCA {
	using pii = pair<int, int>;
	vector<int> depth, par, heavy, head, vid;
	int dfs(int v, int prev, const graph& G) {
		par[v] = prev;
		depth[v] = prev != -1 ? depth[prev] + 1 : 0;
		int ma = 0, cnt = 1;
		for (auto to : G[v]) if (to != prev) {
			int c = dfs(to, v, G);
			if (c > ma) {
				ma = c;
				heavy[v] = to;
			}
			cnt += c;
		}
		return cnt;
	}
public:
	LCA(const graph& G, int rt = 0)
		: depth(G.size()), par(G.size()), heavy(G.size(), -1), head(G.size()), vid(G.size()) {
		dfs(rt, -1, G);
		int id = 0;
		queue<int> q;
		q.push(rt);
		while (!q.empty()) {
			int h = q.front(); q.pop();
			for (int v = h; v != -1; v = heavy[v]) {
				vid[v] = id++;
				head[v] = h;
				for (auto to : G[v]) if (to != par[v] && to != heavy[v]) {
					q.push(to);
				}
			}
		}
	}
	int calc(int u, int v) {
		while (true) {
			if (vid[u] > vid[v]) swap(u, v);
			if (head[u] == head[v]) return u;
			v = par[head[v]];
		}
	}
	int dist(int a, int b) {
		return depth[a] + depth[b] - depth[calc(a, b)] * 2;
	}
};

int main()
{
	ios::sync_with_stdio(false), cin.tie(0);
	int n;
	cin >> n;
	graph G(n);
	for (int i = 0; i < n; i++) {
		int k;
		cin >> k;
		for (int j = 0; j < k; j++) {
			int c;
			cin >> c;
			G[i].push_back(c);
			G[c].push_back(i);
		}
	}
	LCA lca(G);
	int q;
	cin >> q;
	while (q--) {
		int u, v;
		cin >> u >> v;
		printf("%d\n", lca.calc(u, v));
	}
	return 0;
}

