#P10794. 『SpOI - R1』架子鼓可以站 C

『SpOI - R1』架子鼓可以站 C

Problem Description

You are given a tree with nn nodes, where the root is node 11.

You can perform the following “Stand C operation” any number of times. In one “Stand C operation”:

Choose a leaf node xx in the tree, then choose an edge on the path from the root to xx and delete it; after that, add an edge connecting xx and the root.

You need to find the maximum possible diameter of the tree after performing some number of “Stand C operations”.

Note: A leaf node is defined as a node that is not the root and has degree 11.

Input Format

This problem contains multiple test cases.

The first line contains an integer TT, the number of test cases.

Then follow TT test cases. For each test case, the first line contains an integer nn. The second line contains a sequence fif_i of length n1n-1, where the ii-th value is the parent of node i+1i+1 in the tree.

Output Format

For each test case, output one integer per line, the answer.

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

Hint

Explanation of Sample #1

If no operation is performed, the diameter of the tree is 22. It can be proven that this is the maximum diameter.

Explanation of Sample #2

The tree in the sample is as follows:

Only one “Stand C operation” is needed: choose leaf node 66, disconnect the edge from 11 to 44, then connect 66 and 11.

This will make the tree become a chain, with diameter 66. It can be proven that this is the maximum diameter.

Constraints

Please pay attention to how constant factors affect program efficiency.

This problem enables subtask bundling and subtask dependencies.

For all testdata, 1T1041\leq T\leq 10^4, 2n2×1052 \leq n \leq 2\times 10^5, and the input is guaranteed to form a tree.

Subtask TT\leq nn\leq Special property Score Dependency
1 10410^4 1010 None 1515 None
2 2020 1
3 9090 2020 1,2
4 2×1052\times 10^5 AA 1515 None
5 1515 None 3535 1,2,3,4

In particular, for Subtask 4, it is guaranteed that n3×106\sum n\leq 3\times 10^6.

Special property AA: There does not exist a pair (x,y)(x,y) with x1y1x\neq 1\land y\neq 1 such that LCA(x,y)=1\text{LCA}(x,y)=1.

Translated by ChatGPT 5