#include <bits/stdc++.h>
using namespace std;
#define dhoom ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);  
typedef long long ll;
typedef pair<ll,ll> pll;
const ll inf = 99999999999;
const int nax = 1e5 + 7;
int n , q;
vector< int > graph[nax];
int l , timer;
vector< int > tin(nax), tout(nax);
vector<vector<int > >up(nax,vector< int > (30));
bool is_ancestor(int u , int v){
	return (tin[u] <= tin[v] && tout[u] >= tout[v]);
}
int lca(int u , int v){
	if(is_ancestor( u , v))
		return u;
	if(is_ancestor( v, u))
		return v;
	for(int i = l ; i >= 0 ; i--){
		if(!is_ancestor(up[u][i] , v))
			u = up[u][i];
	}
	return up[u][0];
}
void dfs(int u , int p){
	tin[u] = timer++;
	up[u][0] = p;
	for(int i = 1 ; i <= l ; i++)
		up[u][i] = up[up[u][i-1]][i-1];
	for(auto v : graph[u])
	{
		dfs(v , u);
	}
	tout[u] = timer++;
}
int main(){
	dhoom;
	cin >> n ;
	l = ceill(log2(n));
	for(int i = 0 ; i < n ; i++){
		int k;
		cin >> k;
		//cout << "hey" << endl;
		for(int j = 0 ; j < k ; j++){
			int r;
			cin >> r;
			graph[i].push_back(r);
		}
	}
	dfs(0,0);
	cin >> q;
	//up.assign(n + 1 , vector< int > (l+1));
//	cout <<"hey" << endl;
	while(q--){
		int u , v;
		cin >> u >> v;
		cout << lca(u , v) << endl;
	}
    return 0;
}


