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

#LCA0000076. Tổ tiên chung của nhiều đỉnh (Lowest Common Ancestor of a Binary Tree IV)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổ tiên chung của nhiều đỉnh (Lowest Common Ancestor of a Binary Tree IV)

Lowest Common Ancestor of a Binary Tree IV

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

A rooted binary tree is given together with several queries. Each query specifies a set of distinct vertices. Find the deepest vertex that is an ancestor of every specified vertex. A vertex is its own ancestor. The PHOJ version uses integer left/right child indices rather than LeetCode TreeNode pointers.

Input

First line: n rootn\ root. For each vertex ii read Li RiL_i\ R_i (00 means no child). Next read qq. Each query contains kk followed by kk vertex indices.

Output

Print the requested LCA index on a separate line for each query.

Subtasks

General constraints: 1≤n,q≤1051\le n,q\le10^5; 1≤k≤n1\le k\le n; các đỉnh mỗi truy vấn phân biệt; tổng kk trên tất cả truy vấn không vượt 2⋅1052\cdot10^5; chỉ số con thuộc 0..n0..n và mô tả đúng một cây nhị phân.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 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

5 1
2 3
4 5
0 0
0 0
0 0
3
2 4 5
2 4 3
3 3 4 5

Output

2
1
1

Explanation

Vertices 4,54,5 share LCA 22. Adding vertex 33 to the set moves the joint LCA to vertex 11.