PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#LCA0000031. Tổ tiên chung từ danh sách con (Lowest Common Ancestor)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Tổ tiên chung từ danh sách con (Lowest Common Ancestor)

Lowest Common Ancestor

Source: SPOJ

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a rooted tree with nn vertices numbered from 11 to nn. For each vertex, the input directly lists its children; thus the root need not be vertex 1. The root is the unique vertex that is never listed as a child.

For each query (u,v)(u,v), find the lowest common ancestor. Unlike the original SPOJ format with multiple cases and Case X: labels, the PHOJ format contains one dataset and prints only the query answers.

Input

  • First line: nn.
  • For each i=1,…,ni=1,\ldots,n, a line starts with the number of children kik_i, then lists those kik_i child indices.
  • Next line: qq.
  • Last qq lines: query vertices u,vu,v.

Output

Print one LCA per query without any Case X: prefix.

Subtasks

General constraints (all subtasks): 1≤n,q≤10001\le n,q\le 1000; the sum of all child counts is n−1n-1.

  • Subtask 1 (20 points): 1≤n≤301\le n\le 30; 1≤q≤501\le q\le 50.
  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.
  • Subtask 3 (50 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.

Examples

Input

7
3 2 3 4
0
3 5 6 7
0
0
0
0
2
5 7
2 7

Output

3
1

Explanation

Vertices 5,75,7 share parent 33, so the first answer is 33. Vertices 2,72,7 are in different branches of root 11, so the second answer is 11.