CF1856E2.PermuTree (hard version)

普及/提高-

通过率:0%

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

This is the hard 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).

输入格式

The first line contains a single integer nn ( 2n1062 \le n \le 10^6 ).

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 the maximum value of f(a)f(a) .

输入输出样例

  • 输入#1

    5
    1 1 3 3

    输出#1

    4
  • 输入#2

    2
    1

    输出#2

    0
  • 输入#3

    6
    1 2 2 1 5

    输出#3

    7
  • 输入#4

    4
    1 1 1

    输出#4

    2

说明/提示

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:

首页