CF BUDDY
← Problems·

1856E1 · PermuTree (easy version)

1800 · dfs and similar, dp, trees

Problem: This is the easy version of the problem. The differences between the two versions are the constraint on nn and the time limit. You can make hacks only if both versions of the problem are solved.

You are given a tree with nn vertices rooted at vertex 11.

For some permutation^\dagger aa of length nn, let f(a)f(a) be the number of pairs of vertices (u,v)(u, v) such that au<alca(u,v)<ava_u < a_{\operatorname{lca}(u, v)} < a_v. Here, lca(u,v)\operatorname{lca}(u,v) denotes the lowest common ancestor of vertices uu and vv.

Find the maximum possible value of f(a)f(a) over all permutations aa of length nn.

^\dagger A permutation of length nn is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array), and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).

Input Format: The first line contains a single integer nn (2n50002 \le n \le 5000).

The second line contains n1n - 1 integers p2,p3,,pnp_2,p_3,\ldots,p_n (1pi<i1 \le p_i < i) indicating that there is an edge between vertices ii and pip_i.

Output Format: Output the maximum value of f(a)f(a).

Note: The tree in the first test:

One possible optimal permutation aa is [2,1,4,5,3][2, 1, 4, 5, 3] with 44 suitable pairs of vertices:

  • (2,3)(2, 3), since lca(2,3)=1\operatorname{lca}(2, 3) = 1 and 1<2<41 < 2 < 4,
  • (2,4)(2, 4), since lca(2,4)=1\operatorname{lca}(2, 4) = 1 and 1<2<51 < 2 < 5,
  • (2,5)(2, 5), since lca(2,5)=1\operatorname{lca}(2, 5) = 1 and 1<2<31 < 2 < 3,
  • (5,4)(5, 4), since lca(5,4)=3\operatorname{lca}(5, 4) = 3 and 3<4<53 < 4 < 5.

The tree in the third test:

The tree in the fourth test:

Sample Cases

Case 1

Input

5
1 1 3 3

Output

4

Case 2

Input

2
1

Output

0

Case 3

Input

6
1 2 2 1 5

Output

7

Case 4

Input

4
1 1 1

Output

2

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