#include using namespace std; vector> bl; vector> adj; vector depth; int bllog2; void ddfs(int o){ for(int nv : adj[o]){ depth[nv] = depth[o]+1; ddfs(nv); } } int lca(int a, int b){ if(depth[a] < depth[b]) swap(a,b); int k = depth[a] - depth[b]; for(int p = bllog2; p >= 0; p--){ if(k & (1 << p)){ a = bl[a][p]; } } if(a == b) return a; for(int p = bllog2; p >= 0; p--){ if(bl[a][p] != bl[b][p]){ a = bl[a][p], b = bl[b][p]; } } return bl[a][0]; } int main(){ ios::sync_with_stdio(false); int n,q, m, x,y; cin >> n; adj.assign(n, vector()); bllog2 = 32 - __builtin_clz(n); bl.assign(n, vector(bllog2+1)); bl[0][0] = 0; for(int i = 0; i < n; i++){ cin >> m; while(m--){ cin >> x; bl[x][0] = i; adj[i].push_back(x); } } for(int p = 1; p <= bllog2; p++){ for(int i = 0; i < n; i++){ x = bl[i][p-1]; bl[i][p] = bl[x][p-1]; } } depth.resize(n); depth[0] = 0; ddfs(0); cin >> q; while(q--){ cin >> x >> y; cout << lca(x,y) << '\n'; } return 0; }