All problems

Problem 924

Height of Binary Tree After Subtree Removal Queries

Hard · 30 pts · Tree, Depth-First Search, Dynamic Programming

Problem

The tree has N nodes with distinct values 1 to N. Each query names a node Q that is not the root, and asks for the height of the tree (the number of edges on the longest root-to-node path) after removing the whole subtree rooted at Q. Queries are independent: the tree is restored after each one. Precompute, for each node, the best height reachable without entering it, by passing 'the best depth available outside' down the tree from both sides.

Input

The first line contains M, then a line with the M query values. The next two lines describe the tree: N, the number of tokens, then N level-order tokens with 'null' for missing children. The values are 1 to N.

Output

Print M integers separated by spaces, the height after each removal.

Constraints

2 <= N <= 100000; 1 <= M <= 10000; queries are never the root

Example input

1
4
13
1 3 4 2 null 6 5 null null null null null 7

Example output

2

Explanation

In 1 3 4 2 null 6 5 null null null null null 7, removing the subtree of 4 leaves 1 → 3 → 2 as the longest path, so the height becomes 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Binary Tree Longest Consecutive Sequence Next: Equal Tree Partition