J. Removing Leaves
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

For a rooted tree $$$T$$$, define the depth of a node to be the number of edges on the path from the root to it. Also, define $$$f(T)$$$ as the sum of depths of all the nodes in the tree.

You are given a rooted tree $$$T$$$ with $$$N$$$ nodes numbered $$$1, 2, \ldots, N$$$, rooted at node $$$1$$$. For $$$i \ge 2$$$, the parent of node $$$i$$$ is $$$p_i$$$. It is given that $$$p_i \lt i$$$ for all $$$i \ge 2$$$.

You want to remove all nodes from the tree one by one until only the root remains. In a single step, you can remove any leaf node (a non-root node which has exactly one adjacent node). Note that a node which is not a leaf node initially can become a leaf node later and become eligible for removal.

In this process, let $$$T_0$$$(the original tree), $$$T_1, T_2, \ldots T_{n-1}$$$(the tree with only the root remaining) be the sequence of trees formed. In other words, $$$T_i$$$ is the tree formed after $$$i$$$ nodes have been removed. What is the maximum possible value of $$$\displaystyle \sum_{i=0}^{n-1} f(T_i)$$$?

Input

The first line contains $$$Q(1 \le Q \le 40)$$$, the number of test-cases. Then the testcases follow, each containing two lines:

  • The first line contains $$$N(1 \le N \le 40)$$$, the number of nodes in the tree.
  • The second line contains $$$N - 1$$$ space separated integers $$$p_2, p_3, \ldots p_N$$$, such that $$$1 \le p_i \lt i$$$ for all $$$i = 2, 3, \ldots N$$$.

The sum of $$$N$$$ over all test-cases does not exceed $$$40$$$.

Output

For each testcase, print the maximum possible value of $$$\displaystyle \sum_{i=0}^{n-1} f(T_i) $$$ on a new line.

Example
Input
2
4
1 1 1
5
1 2 2 1
Output
6
15
Note

In the first testcase, the depth of node $$$1$$$ is $$$0$$$, and that of nodes $$$2, 3, 4$$$ are $$$1$$$. If we remove the nodes in the order $$$2, 3, 4$$$, the objective value is $$$(0 + 1 + 1 + 1) + (0 + 1 + 1) + (0 + 1) + 0 = 6$$$. This is the maximum possible value, and so is the answer.

In the second testcase, the depths of nodes $$$1, 2, 3, 4, 5$$$ are $$$0, 1, 2, 2, 1$$$ respectively. We can remove nodes in the order $$$5, 3, 4, 2$$$ to get the objective value as $$$6 + 5 + 3 + 1 + 0 = 15$$$. The sequence $$$T_0, T_1, \ldots T_4$$$ is :