#include <bits/stdc++.h>
using Int = int64_t;
using UInt = uint64_t;
using C = std::complex<double>;
#define rep(i, n) for(Int i = 0; i < (Int)(n); ++i)
#define guard(x) if( not (x) ) continue;
#ifndef LOCAL_
#define fprintf if( false ) fprintf
#endif

int main() {
   Int n;
   std::cin >> n;
   Int m = log2(n) + 1.1;
   std::vector<std::vector<Int>> xss(m, std::vector<Int>(n,0));
   std::vector<Int> hs(n);
   xss[0][0] = 0;
   hs[0] = 0;
   rep(i, n) {
      Int a;
      std::cin >> a;
      rep(k, a) {
         Int c;
         std::cin >> c;
         xss[0][c] = i;
         hs[c] = hs[i] + 1;
      }
   }
   for(Int i = 1; i < m; ++i) {
      rep(k, n) {
         xss[i][k] = xss[i-1][xss[i-1][k]];
      }
   }
   Int q;
   std::cin >> q;
   rep(i, q) {
      Int a, b;
      std::cin >> a >> b;
      if( hs[a] > hs[b] ) std::swap(a, b);
      if( hs[a] < hs[b] ) {
         Int diff = hs[b] - hs[a];
         rep(k, m) {
            guard( ( diff & ((Int)1 << k) ) != 0 );
            b = xss[k][b];
         }
      }
      assert( hs[a] == hs[b] );
      if( a == b ) {
         printf("%ld\n", a);
         continue;
      }
      for(Int k = m - 1; k >= 0; --k) {
         if( xss[k][a] != xss[k][b] ) {
            a = xss[k][a];
            b = xss[k][b];
         }
      }
      assert( xss[0][a] == xss[0][b] );
      printf("%ld\n", xss[0][a]);
   }
}

