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_use]
mod input_mcr {
    // ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
    // diff: using Parser
    #[macro_export(local_inner_macros)]
    macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

    #[macro_export(local_inner_macros)]
    macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

    #[macro_export(local_inner_macros)]
    macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, char_) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()[0]
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, line) => {
        $parser.next_line()
    };
    ($parser:ident, line_) => {
        $parser.next_line().chars().collect::<Vec<char>>()
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

    use std::io;
    use std::io::BufRead;
    use std::str;

    // ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
    // ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
    // diff: using std::io::BufRead::fill_buf()
    pub struct Parser<R> {
        pub reader: R,
        buf: Vec<u8>,
        pos: usize,
    }

    impl Parser<io::Empty> {
        pub fn from_str(s: &str) -> Parser<io::Empty> {
            Parser {
                reader: io::empty(),
                buf: s.as_bytes().to_vec(),
                pos: 0,
            }
        }
    }

    impl<R: BufRead> Parser<R> {
        pub fn new(reader: R) -> Parser<R> {
            Parser {
                reader: reader,
                buf: vec![],
                pos: 0,
            }
        }
        pub fn update_buf(&mut self) {
            self.buf.clear();
            self.pos = 0;
            loop {
                let (len, complete) = {
                    let buf2 = self.reader.fill_buf().unwrap();
                    self.buf.extend_from_slice(buf2);
                    let len = buf2.len();
                    (len, buf2[len - 1] <= 0x20)
                };
                self.reader.consume(len);
                if complete {
                    break;
                }
            }
        }
        pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
            loop {
                let mut begin = self.pos;
                while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                    begin += 1;
                }
                let mut end = begin;
                while end < self.buf.len() && (self.buf[end] > 0x20) {
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
                } else {
                    self.update_buf();
                }
            }
        }
        pub fn next_line(&mut self) -> String {
            loop {
                let mut begin = self.pos;
                if begin < self.buf.len() && (self.buf[begin] < 0x20) {
                    begin += 1;
                }
                let mut end = begin;
                while end < self.buf.len() && (self.buf[end] >= 0x20) {
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.to_string();
                } else {
                    self.update_buf();
                }
            }
        }
        pub fn fast_i64(&mut self) -> i64 {
            loop {
                let mut begin = self.pos;
                while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                    begin += 1;
                }
                if begin == self.buf.len() {
                    self.update_buf();
                    continue;
                }
                let mut res = 0;
                let (is_positive, mut end) = match self.buf[begin] {
                    b'+' => (true, begin + 1),
                    b'-' => (false, begin + 1),
                    _ => (true, begin),
                };
                while end < self.buf.len() && (self.buf[end] > 0x20) {
                    res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                    end += 1;
                }
                if begin != self.buf.len() {
                    self.pos = end;
                    return if is_positive { res } else { -res };
                } else {
                    self.update_buf();
                }
            }
        }
    }
}

mod unionfind {
    struct UnionFindNode {
        parent: usize,
        num: usize,
    }

    impl UnionFindNode {
        fn new(parent: usize) -> UnionFindNode {
            UnionFindNode {
                parent: parent,
                num: 1,
            }
        }
    }

    pub struct UnionFind(Vec<UnionFindNode>);

    impl UnionFind {
        pub fn new(n: usize) -> UnionFind {
            let mut xs = vec![];
            for i in 0..n {
                xs.push(UnionFindNode::new(i));
            }
            UnionFind(xs)
        }
        pub fn root(&mut self, i: usize) -> usize {
            let parent = self.0[i].parent;
            if parent == i {
                i
            } else {
                let res = self.root(parent);
                self.0[i].parent = res;
                res
            }
        }
        pub fn unite(&mut self, i: usize, k: usize) {
            let i = self.root(i);
            let k = self.root(k);
            if i == k {
                return;
            }
            let (i, k) = if self.0[i].num < self.0[k].num {
                (i, k)
            } else {
                (k, i)
            };
            self.0[i].parent = k;
            self.0[k].num += self.0[i].num;
        }
        pub fn is_same_set(&mut self, i: usize, k: usize) -> bool {
            self.root(i) == self.root(k)
        }
        pub fn num(&mut self, i: usize) -> usize {
            let i = self.root(i);
            self.0[i].num
        }
    }
}

use input_mcr::*;
use std::cmp::*;

use unionfind::*;

struct RootedTreeWithLCA {
    parent: Vec<Vec<usize>>,
    depth: Vec<usize>,
}

impl RootedTreeWithLCA {
    pub fn new(ps: &[usize]) -> RootedTreeWithLCA {
        let n = ps.len();
        let m = n.next_power_of_two().trailing_zeros() as usize + 1;
        let mut parent = vec![vec![]; m];
        for k in 0..n {
            parent[0].push(ps[k]);
        }
        for i in 1..m {
            for k in 0..n {
                let a = parent[i - 1][k];
                let b = parent[i - 1][a];
                parent[i].push(b);
            }
        }
        let mut graph = vec![vec![]; n];
        for i in 0..n {
            graph[ps[i]].push(i);
        }
        let inf = 1 << 50;
        let mut depth = vec![inf; n];
        depth[0] = 0;
        let mut q = std::collections::VecDeque::new();
        q.push_back(0);
        while let Some(v) = q.pop_front() {
            for &next in &graph[v] {
                if depth[v] + 1 < depth[next] {
                    depth[next] = depth[v] + 1;
                    q.push_back(next);
                }
            }
        }
        // eprintln!("depth = {:?}", depth);
        RootedTreeWithLCA {
            parent: parent,
            depth: depth,
        }
    }
    pub fn lca(&self, x: usize, y: usize) -> usize {
        let (mut x, mut y) = if self.depth[x] <= self.depth[y] {
            (x, y)
        } else {
            (y, x)
        };
        let m = self.parent.len();
        //// eprintln!("(1): x = {}, y = {}", x, y);
        for i in (0..m).rev() {
            if (self.depth[y] - self.depth[x]) & (1 << i) != 0 {
                y = self.parent[i][y];
            }
        }
        //// eprintln!("(2): x = {}, y = {}", x, y);
        if x == y {
            return x;
        }
        assert_eq!(self.depth[x], self.depth[y]);
        for i in (0..m).rev() {
            if self.parent[i][x] != self.parent[i][y] {
                x = self.parent[i][x];
                y = self.parent[i][y];
            }
        }
        //// eprintln!("(3): x = {}, y = {}", x, y);
        assert_eq!(self.parent[0][x], self.parent[0][y]);
        self.parent[0][x]
    }
    pub fn dist(&self, x: usize, y: usize) -> usize {
        self.depth[x] + self.depth[y] - 2 * self.depth[self.lca(x, y)]
    }
}

fn two_edge_connected_components(
    n: usize,
    es: &[(usize, usize)],
) -> (UnionFind, RootedTreeWithLCA) {
    let mut graph = vec![vec![]; n];
    for &(s, t) in es {
        graph[s].push(t);
        graph[t].push(s);
    }

    fn dfs(
        graph: &Vec<Vec<usize>>,
        i: usize,
        prev: Option<usize>,
        count: &mut Vec<i64>,
        ds: &mut Vec<Option<i64>>,
        uf: &mut UnionFind,
        new_edges: &mut Vec<(usize, usize)>,
    ) -> i64 {
        for &next in &graph[i] {
            if Some(next) == prev {
                continue;
            }
            if ds[next].is_none() {
                ds[next] = Some(ds[i].unwrap() + 1);
                let t = dfs(graph, next, Some(i), count, ds, uf, new_edges);
                // eprintln!("fe: {} -> {}, t = {}", i, next, t);
                count[i] += t;
                if t != 0 {
                    uf.unite(i, next);
                } else {
                    new_edges.push((i, next));
                }
            } else if ds[next].unwrap() < ds[i].unwrap() {
                // eprintln!("be: {}+1, {}-1", next, i);
                count[next] += 1;
                count[i] -= 1;
            }
        }
        count[i]
    }

    let mut count = vec![0; n];
    let mut ds = vec![None; n];
    ds[0] = Some(0);
    let mut uf = UnionFind::new(n);
    let mut new_edges = vec![];
    dfs(
        &graph,
        0,
        None,
        &mut count,
        &mut ds,
        &mut uf,
        &mut new_edges,
    );
    let mut ps: Vec<usize> = (0..n).collect();
    for &(s, t) in &new_edges {
        ps[uf.root(t)] = uf.root(s);
    }
    // eprintln!("ps = {:?}", ps);
    (uf, RootedTreeWithLCA::new(&ps))
}

fn main() {
    input! {
        new_stdin_parser = parser,
        n: usize,
    }
    let mut ps: Vec<usize> = (0..n).collect();
    for i in 0..n {
        input! {
            parser = parser,
            m: usize,
            xs: [usize; m],
        }
        for &x in &xs {
            ps[x] = i;
        }
    }
    let r_tree = RootedTreeWithLCA::new(&ps);
    input! {
        parser = parser,
        q: usize,
        qs: [(usize,usize); q],
    }
    for &(s, t) in &qs {
        println!("{}", r_tree.lca(s, t));
    }
}

fn main2() {
    input! {
        n: usize,
        m: usize,
        es: [(usize1,usize1); m],
        q: usize,
        qs: [(usize1,usize1,usize1); q],
    }
    let (mut uf, r_tree) = two_edge_connected_components(n, &es);
    for i in 0..n {
        // eprintln!("root of {} = {}", i, uf.root(i));
    }
    for &(a, b, c) in &qs {
        let a = uf.root(a);
        let b = uf.root(b);
        let c = uf.root(c);
        // eprintln!("a = {}, b = {}, c = {}", a, b, c);
        //// eprintln!("a^b = {}", r_tree.lca(a,b));
        //// eprintln!("b^a = {}", r_tree.lca(b,a));
        //// eprintln!("a^c = {}", r_tree.lca(a,c));
        //// eprintln!("c^a = {}", r_tree.lca(c,a));
        //// eprintln!("b^c = {}", r_tree.lca(b,c));
        //// eprintln!("c^b = {}", r_tree.lca(c,b));
        let res = r_tree.dist(a, b) + r_tree.dist(b, c) == r_tree.dist(a, c);
        println!("{}", if res { "OK" } else { "NG" });
    }
}