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

#LCA0000034. Tổ tiên chung trên cây gốc 0 (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 trên cây gốc 0 (Lowest Common Ancestor)

Lowest Common Ancestor

Source: AOJ

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a tree rooted at vertex 00, with vertices indexed 00 through n−1n-1. For each node, its direct children are listed. For each pair u,vu,v, find the deepest vertex that is an ancestor of both.

Every node counts as its own ancestor. Vertex indices start at 00, and the tree may be very deep.

Input

  • First line: nn.
  • The next nn lines describe vertex ii with kik_i and then its kik_i child indices.
  • Next line: qq.
  • Next qq lines: u,vu,v.

Output

Print each query LCA.

Subtasks

General constraints (all subtasks): 1≤n,q≤1051\le n,q\le 10^5; 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≤1000001\le n\le 100000; 1≤q≤1000001\le q\le 100000.

Examples

Input

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

Output

1
1
0
0

Explanation

Vertices 4,64,6 have LCA 11. Vertices 5,25,2 belong to separate branches of root 00, giving LCA 00.