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

#LCA0000032. Tổ tiên chung trên cây đánh số từ 0 (Lowest Common Ancestor (0-indexed))

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổ tiên chung trên cây đánh số từ 0 (Lowest Common Ancestor (0-indexed))

Lowest Common Ancestor (0-indexed)

Source: SPOJ

Version: Phuoc Hung OJ Extended

Problem Statement

A tree has nn vertices indexed from 00 to n−1n-1, rooted at vertex 00. The input directly lists each node's children. Answer qq lowest-common-ancestor queries on node pairs u,vu,v.

Here vertex 0 is a valid node and is the root; it is not a missing-node sentinel. For equal query endpoints, the answer is the endpoint itself.

Input

  • First line: nn.
  • Next nn lines describe vertices 0,1,…,n−10,1,\ldots,n-1 with child count kik_i followed by their indices.
  • Next line: qq.
  • Last qq lines: u,vu,v.

Output

Print one answer per line.

Subtasks

General constraints (all subtasks): 1≤n,q≤1041\le n,q\le 10^4; 0≤u,v<n0\le u,v<n.

  • 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≤100001\le n\le 10000; 1≤q≤100001\le q\le 10000.

Examples

Input

3
2 1 2
0
0
3
1 2
1 1
2 2

Output

0
1
2

Explanation

Vertex 00 is the common ancestor of 11 and 22. Same-vertex queries return 11 and 22 respectively.