Problem:
LCA: Lowest Common Ancestor

For a rooted tree, find the lowest common ancestor of two nodes u and v.

The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.

Input

n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.

In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.

Output

For each query, print the LCA of u and v in a line.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

Sample Input 1

8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2

Sample Output 1

1
1
0
0

Solution in Rust (judge verdict: Accepted)

macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; ( iter = $ iter : ident , $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut $ iter = s . split_whitespace ( ) ; input_inner ! { $ iter , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut iter = s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; }
macro_rules ! input_inner { ( $ iter : expr ) => { } ; ( $ iter : expr , ) => { } ; ( $ iter : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , mut $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , mut $ var : usize $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , $ var : usize $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ iter : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ iter , $ t ) ) ,* ) } ; ( $ iter : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ iter , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ iter : expr , { chars : $ base : expr } ) => { read_value ! ( $ iter , String ) . chars ( ) . map ( | c | ( c as u8 - $ base as u8 ) as usize ) . collect ::< Vec < usize >> ( ) } ; ( $ iter : expr , { char : $ base : expr } ) => { read_value ! ( $ iter , { chars : $ base } ) [ 0 ] } ; ( $ iter : expr , chars ) => { read_value ! ( $ iter , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ iter : expr , char ) => { read_value ! ( $ iter , chars ) [ 0 ] } ; ( $ iter : expr , usize1 ) => { read_value ! ( $ iter , usize ) - 1 } ; ( $ iter : expr , $ t : ty ) => { $ iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) } ; }
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Adjacent {
    pub to: usize,
    pub id: usize,
}
impl Adjacent {
    pub fn new(to: usize, id: usize) -> Adjacent {
        Adjacent { to: to, id: id }
    }
}
#[derive(Clone, Debug, Default)]
pub struct Graph {
    pub vsize: usize,
    pub esize: usize,
    pub graph: Vec<Vec<Adjacent>>,
}
impl Graph {
    pub fn new(vsize: usize) -> Graph {
        Graph {
            vsize: vsize,
            esize: 0,
            graph: vec![vec![]; vsize],
        }
    }
    pub fn add_edge(&mut self, from: usize, to: usize) {
        self.graph[from].push(Adjacent::new(to, self.esize));
        self.esize += 1;
    }
    pub fn add_undirected_edge(&mut self, u: usize, v: usize) {
        self.graph[u].push(Adjacent::new(v, self.esize));
        self.graph[v].push(Adjacent::new(u, self.esize));
        self.esize += 1;
    }
    pub fn vertexes(&self) -> std::ops::Range<usize> {
        0..self.vsize
    }
    pub fn adjacency(&self, from: usize) -> &Vec<Adjacent> {
        &self.graph[from]
    }
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Vertex {
    l: usize,
    r: usize,
    d: i64,
    p: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Edge {
    l: usize,
    r: usize,
}
#[derive(Clone, Debug, Default)]
pub struct EulerTourTree {
    root: usize,
    vs: Vec<Vertex>,
    es: Vec<Edge>,
    vtrace: Vec<usize>,
    etrace: Vec<usize>,
}
impl EulerTourTree {
    pub fn new() -> Self {
        Default::default()
    }
    fn euler_tour(&mut self, u: usize, p: usize, d: i64, graph: &Graph) {
        self.vs[u].l = self.vtrace.len();
        self.vs[u].d = d;
        self.vtrace.push(u);
        for a in graph.adjacency(u) {
            if a.to != p {
                self.es[a.id].l = self.etrace.len();
                self.etrace.push(a.id);
                self.euler_tour(a.to, u, d + 1, graph);
                self.vtrace.push(u);
                self.es[a.id].r = self.etrace.len();
                self.etrace.push(a.id);
                self.vs[a.to].p = a.id;
            }
        }
        self.vs[u].r = self.vtrace.len() - 1;
    }
    pub fn build(&mut self, root: usize, graph: &Graph) {
        let n = graph.vsize;
        self.root = root;
        self.vs = vec![Default::default(); n];
        self.es = vec![Default::default(); n - 1];
        self.vtrace.clear();
        self.etrace.clear();
        self.euler_tour(root, n, 0, graph);
    }
    pub fn vertex_in_range(&self, u: usize, v: usize) -> (usize, usize) {
        let (mut l, mut r) = (self.vs[u].l, self.vs[v].l);
        if l > r {
            std::mem::swap(&mut l, &mut r);
        }
        (l, r + 1)
    }
    pub fn subtree_range(&self, u: usize) -> (usize, usize) {
        (self.vs[u].l, self.vs[u].r + 1)
    }
}
#[derive(Clone, Debug)]
pub struct SegmentTree<M: Monoid> {
    pub n: usize,
    pub seg: Vec<M::T>,
    pub m: M,
}
impl<M: Monoid> SegmentTree<M> {
    pub fn new(n: usize, m: M) -> SegmentTree<M> {
        let n = 1 << format!("{:b}", n - 1).len();
        let seg = vec![m.mempty(); 2 * n - 1];
        SegmentTree {
            n: n,
            seg: seg,
            m: m,
        }
    }
    pub fn from_vec(v: Vec<M::T>, m: M) -> SegmentTree<M> {
        let n = 1 << format!("{:b}", v.len() - 1).len();
        let mut seg = vec![m.mempty(); 2 * n - 1];
        for (i, x) in v.into_iter().enumerate() {
            seg[i + n - 1] = x;
        }
        for i in (0..n - 1).rev() {
            seg[i] = m.mappend(&seg[2 * i + 1], &seg[2 * i + 2]);
        }
        SegmentTree {
            n: n,
            seg: seg,
            m: m,
        }
    }
    pub fn update(&mut self, k: usize, x: M::T) {
        let mut k = k + self.n - 1;
        self.seg[k] = x;
        while k > 0 {
            k = (k - 1) / 2;
            self.seg[k] = self.m.mappend(&self.seg[2 * k + 1], &self.seg[2 * k + 2]);
        }
    }
    pub fn query(&self, l: usize, r: usize) -> M::T {
        let mut l = l + self.n - 1;
        let mut r = r + self.n - 1;
        let mut vl = self.m.mempty();
        let mut vr = self.m.mempty();
        while l < r {
            if l & 1 == 0 {
                vl = self.m.mappend(&vl, &self.seg[l]);
                l += 1;
            }
            if r & 1 == 0 {
                r -= 1;
                vr = self.m.mappend(&self.seg[r], &vr);
            }
            l = (l - 1) / 2;
            r = (r - 1) / 2;
        }
        self.m.mappend(&vl, &vr)
    }
}
pub trait Monoid {
    type T: Clone + PartialEq;
    fn mempty(&self) -> Self::T;
    fn mappend(&self, x: &Self::T, y: &Self::T) -> Self::T;
}
#[derive(Clone, Debug)]
pub struct LCAMonoid<'a> {
    euler: &'a EulerTourTree,
}
impl<'a> Monoid for LCAMonoid<'a> {
    type T = usize;
    fn mempty(&self) -> usize {
        self.euler.vs.len()
    }
    fn mappend(&self, u: &usize, v: &usize) -> usize {
        self.euler.ancestor(*u, *v)
    }
}
#[derive(Clone, Debug)]
pub struct LowestCommonAncestor<'a> {
    seg: SegmentTree<LCAMonoid<'a>>,
    euler: &'a EulerTourTree,
}
impl<'a> LowestCommonAncestor<'a> {
    pub fn lca(&self, u: usize, v: usize) -> usize {
        let (l, r) = self.euler.vertex_in_range(u, v);
        self.seg.query(l, r)
    }
}
impl EulerTourTree {
    pub fn ancestor(&self, u: usize, v: usize) -> usize {
        if u >= self.vs.len() {
            v
        } else if v >= self.vs.len() {
            u
        } else if self.vs[u].d < self.vs[v].d {
            u
        } else {
            v
        }
    }
    pub fn gen_lca<'a>(&'a self) -> LowestCommonAncestor<'a> {
        LowestCommonAncestor {
            seg: SegmentTree::from_vec(self.vtrace.clone(), LCAMonoid { euler: self }),
            euler: self,
        }
    }
}
#[allow(unused_imports)]
use std::io::{stdout, BufWriter, StdoutLock, Write};
fn with_bufwriter<F: FnOnce(&mut BufWriter<StdoutLock>) -> std::io::Result<()>>(
    f: F,
) -> std::io::Result<()> {
    let stdout = stdout();
    let mut writer = BufWriter::new(stdout.lock());
    f(&mut writer)
}
fn main() {
    input! { iter = iter, n };
    let mut g = Graph::new(n);
    let mut e = EulerTourTree::new();
    for u in 0..n {
        input_inner! { iter, k, c: [usize; k] };
        for i in 0..k {
            g.add_undirected_edge(u, c[i]);
        }
    }
    e.build(0, &g);
    let lca = e.gen_lca();
    input_inner! { iter, q, uv: [(usize, usize); q] };
    with_bufwriter(|out| {
        for &(u, v) in uv.iter() {
            writeln!(out, "{}", lca.lca(u, v))?;
        }
        Ok(())
    })
    .unwrap();
}