#include <stdio.h>
#include <stdlib.h>

#define MAX_NODE (100000)

int* node[MAX_NODE];
int n_size[MAX_NODE] = {0};
int parent[MAX_NODE] = {0};
int is_visits[MAX_NODE];
int _result;
int _root;

int solve(int source, int sink, int now_node, int p_node) {
	int i,size,result;
	if(is_visits[now_node] == 1) return -1;
	if(now_node == sink) return p_node;
	if(_root == now_node) {
		_result = _root;
		return _root;
	}

	is_visits[now_node] = 1;
	for(i=0,size=n_size[now_node];i<size;i++) {
		if(sink == node[now_node][i]) {
			_result = p_node;
			return p_node;
		}
		if(is_visits[node[now_node][i]] == 1) continue;
		
		result = solve(source, sink, node[now_node][i], p_node);
		if(sink == result) {
			_result = p_node;
			return p_node;
		}
	}
	
	if(_result >= 0) {
		return _result;
	}
	return solve(source, sink, parent[now_node], parent[now_node]);
}

int main(void) {
	int i, j, x, m, n, q;
	int source, sink;
	int is_root[MAX_NODE] = {0};
	
	scanf("%d\n", &n);
	for(i=0;i<n;i++) {
		scanf("%d", &m);
		n_size[i] = m;
		if(m>0) node[i] = (int*)malloc(m*sizeof(int));
		
		for(j=0;j<m;j++) {
			scanf("%d", &node[i][j]);
			is_root[node[i][j]] = -1;
			parent[node[i][j]] = i;
		}
	}
	
	// ルート
	for(i=0;i<n;i++) {
		if(is_root[i] == 0) {
			_root = i;
			break;
		}
	}
	
	scanf("%d\n", &q);
	for(i=0;i<q;i++) {
		_result = -1;
		for(j=0;j<n;j++) is_visits[j] = 0;	// 訪れたかどうか
		scanf("%d %d\n" ,&source, &sink);
		if(source == sink) {
			printf("%d\n", source);
		} else {
			printf("%d\n", solve(source, sink, source, source));
		}
	}

	return 0;
}