CF BUDDY
← Problems·

1994E · Wooden Game

2000 · bitmasks, greedy, math

Problem: You are given a forest of kk rooted trees*^{\text{*}}. Lumberjack Timofey wants to cut down the entire forest by applying the following operation:

  • Select a subtree^{\text{†}} of any vertex of one of the trees and remove it from the tree.

Timofey loves bitwise operations, so he wants the bitwise OR of the sizes of the subtrees he removed to be maximum. Help him and find the maximum result he can obtain.

Input Format: Each test consists of multiple test cases. The first line contains an integer tt (1t1041 \leq t \leq 10^4) — the number of test cases. Then follows the description of the test cases.

The first line of each test case contains a single integer kk (1k1061 \leq k \leq 10^6) — the number of trees in the forest.

This is followed by a description of each of the kk trees:

The first line contains a single integer nn (1n1061 \leq n \leq 10^6) — the size of the tree. The vertices of the tree are numbered with integers from 11 to nn. The root of the tree is vertex number 11.

The second line contains n1n - 1 integers p2,p3,pnp_2, p_3, \ldots p_n (1pi<i1 \leq p_i < i), where pip_i — the parent of vertex ii.

It is guaranteed that the sum of kk and nn for all sets of input data does not exceed 10610^6.

Output Format: For each test case, output a single integer — the maximum result that can be obtained.

Note: In the second test case, the trees look like this:

The first operation removes the entire second tree.

The second operation removes vertex 44 from the first tree.

The third operation removes the first tree. The result is 613=76|1|3 = 7 (| denotes bitwise OR).

In the third test case, the entire tree needs to be removed.

Sample Cases

Case 1

Input

3
1
1
2
4
1 2 2
6
1 1 3 1 3
1
10
1 2 2 1 1 5 7 6 4

Output

1
7
10

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback