atcoder#AGC023F. [AGC023F] 01 on Tree

[AGC023F] 01 on Tree

Score : 17001700 points

Problem Statement

Snuke has a rooted tree with NN vertices, numbered 11 through NN. Vertex 11 is the root of the tree, and the parent of Vertex ii ( 2iN2\leq i \leq N ) is Vertex PiP_i ( Pi<iP_i < i ). There is a number, 00 or 11, written on each vertex. The number written on Vertex ii is ViV_i.

Snuke would like to arrange the vertices of this tree in a horizontal row. Here, for every vertex, there should be no ancestor of that vertex to the right of that vertex.

After arranging the vertices, let XX be the sequence obtained by reading the numbers written on the vertices from left to right in the arrangement. Snuke would like to minimize the inversion number of XX. Find the minimum possible inversion number of XX.

Notes

The inversion number of a sequence ZZ whose length NN is the number of pairs of integers ii and jj ( 1i<jN1 \leq i < j \leq N ) such that Zi>ZjZ_i > Z_j.

Constraints

  • 1N2×1051 \leq N \leq 2 \times 10^5
  • 1Pi<i1 \leq P_i < i ( 2iN2 \leq i \leq N )
  • 0Vi10 \leq V_i \leq 1 ( 1iN1 \leq i \leq N )
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

P2P_2 P3P_3 ...... PNP_N

V1V_1 V2V_2 ...... VNV_N

Output

Print the minimum possible inversion number of XX.

6
1 1 2 3 3
0 1 1 0 0 0
4

When the vertices are arranged in the order 1,3,5,6,2,41, 3, 5, 6, 2, 4, XX will be (0,1,0,0,1,0)(0, 1, 0, 0, 1, 0), whose inversion number is 44. It is impossible to have fewer inversions, so the answer is 44.

1

0
0

X=(0)X = (0), whose inversion number is 00.

15
1 2 3 2 5 6 2 2 9 10 1 12 13 12
1 1 1 0 1 1 0 0 1 0 0 1 1 0 0
31