#include <stdio.h>
#include <vector>
#include <utility>
using namespace std;

constexpr int kN = int(1E5 + 10);

#define PB push_back
#define F first
#define S second

vector<int> graph[kN];
vector<pair<int, int>> que[kN];
int p[kN], ans[kN];
bool went[kN];

int Find(int n) {return p[n] == n ? n : p[n] = Find(p[n]);}

void dfs(int pos) {
	went[pos] = true;
	for (int i : graph[pos]) {
		dfs(i);
		p[i] = pos;
	}
	for (pair<int, int> i : que[pos]) if (went[i.F]) ans[i.S] = Find(i.F);
	return ;
}

int main() {
	int n, k, l, r, tmp, q;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d", &k);
		while (k--) {
			scanf("%d", &tmp);
			graph[i].PB(tmp);
		}
	}
	
	for (int i = 0; i < n; i++) p[i] = i;
	for (int i = 0; i < n; i++) went[i] = false;

	scanf("%d", &q);
	for (int i = 0; i < q; i++)	{
		scanf("%d%d", &l, &r);
		que[l].PB({r, i});
		que[r].PB({l, i});
	}

	dfs(0);

	for (int i = 0; i < q; i++) printf("%d\n", ans[i]);
}

