Codeforces Round 890 (Div. 2) supported by Constructor Institute
E1
PermuTree (easy version)
Codeforces
1800
原题
← DE2 →
翻译中…

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

翻译中…

You are given a tree with $n$ vertices rooted at vertex $1$.

翻译中…

For some permutation$^\dagger$ $a$ of length $n$, let $f(a)$ be the number of pairs of vertices $(u, v)$ such that $a_u \lt a_{\operatorname{lca}(u, v)} \lt a_v$. Here, $\operatorname{lca}(u,v)$ denotes the lowest common ancestor of vertices $u$ and $v$.

翻译中…

Find the maximum possible value of $f(a)$ over all permutations $a$ of length $n$.

翻译中…

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

翻译中…

Input

翻译中…

The first line contains a single integer $n$ ($2 \le n \le 5000$).

翻译中…

The second line contains $n - 1$ integers $p_2,p_3,\ldots,p_n$ ($1 \le p_i \lt i$) indicating that there is an edge between vertices $i$ and $p_i$.

翻译中…

Output

翻译中…

Output the maximum value of $f(a)$.

翻译中…

Note

翻译中…

The tree in the first test:

翻译中…

image

翻译中…

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

翻译中…
  • $(2, 3)$, since $\operatorname{lca}(2, 3) = 1$ and $1 \lt 2 \lt 4$,
  • $(2, 4)$, since $\operatorname{lca}(2, 4) = 1$ and $1 \lt 2 \lt 5$,
  • $(2, 5)$, since $\operatorname{lca}(2, 5) = 1$ and $1 \lt 2 \lt 3$,
  • $(5, 4)$, since $\operatorname{lca}(5, 4) = 3$ and $3 \lt 4 \lt 5$.
翻译中…

The tree in the third test:

翻译中…

image

翻译中…

The tree in the fourth test:

翻译中…

image

翻译中…

样例

Input #1
5
1 1 3 3
Output #1
4
InputCopy OutputCopy
Input #2
2
1
Output #2
0
InputCopy OutputCopy
Input #3
6
1 2 2 1 5
Output #3
7
InputCopy OutputCopy
Input #4
4
1 1 1
Output #4
2
InputCopy OutputCopy
题目信息
题号
1856E1
时间限制
2 s
内存限制
512 MB
标签
DFS 及类似
动态规划
树

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。