#P13954. [ICPC 2023 Nanjing R] 红黑树

    ID: 13902 远端评测题 2000ms 1024MiB 尝试: 0 已通过: 0 难度: 8 上传者: 标签>动态规划 DP2023ICPC南京斜率维护技巧 slope trick

[ICPC 2023 Nanjing R] 红黑树

Description

There is a rooted tree with nn vertices numbered from 11 to nn, where vertex 11 is the root. Each vertex has a color, which is either red or black.

We say a vertex is good, if every simple path from that vertex to any of its descendant leaf vertex contains the same number of black vertices. We say a tree is perfect, if all its vertices are good.

Let RkR_k be the subtree rooted at vertex kk. For each 1kn1 \le k \le n, answer the following query: If you can choose a set of vertices and change their colors (that is, change red vertices to black, and change black vertices to red), calculate the minimum number of vertices you have to choose to make RkR_k perfect.

Recall that a simple path is a path which does not go through the same edge multiple times.

Also recall that a subtree rooted at vertex kk is a tree consisting of all descendants of vertex kk and has vertex kk as the root. Note that any vertex is a descendant of itself.

Input Format

There are multiple test cases. The first line of the input contains an integer TT indicating the number of test cases. For each test case:

The first line contains an integer nn (2n1052 \le n \le 10^5) indicating the number of vertices in the tree.

The second line contains a string s1s2sns_1s_2\cdots s_n of length nn (si{0,1}s_i \in \{0, 1\}). If si=0s_i = 0 then vertex ii is red; If si=1s_i = 1 then vertex ii is black.

The third line contains (n1)(n - 1) integers p2,p3,,pnp_2, p_3, \cdots, p_n (1pi<i1 \le p_i < i) where pip_i is the parent of vertex ii.

It's guaranteed that the sum of nn of all test cases will not exceed 10610^6.

Output Format

For each test case output one line containing nn integers separated by a space, where the ii-th integer indicates the minimum number of vertices whose color you have to change to make RiR_i perfect.

Please, DO NOT output extra spaces at the end of each line, or your solution may be considered incorrect!

2
9
101011110
1 1 3 3 3 6 2 2
4
1011
1 1 3
4 1 2 0 0 0 0 0 0
2 0 0 0

Hint

:::align{center} :::

We illustrate the first sample test case.

To make R1R_1 perfect, we can change the color of vertices 22, 44, 66 and 99. After that, all paths from vertex 11 to its descendant leaves will contain 33 black vertices, all paths from vertex 22 to its descendant leaves will contain 22 black vertices, and all paths from vertex 33 to its descendant leaves will contain 22 black vertices. As vertices 44 to 99 only has one descendant leaf, they're always good.

To make R2R_2 perfect, we can change the color of vertex 88. After that, all paths from vertex 22 to its descendant leaves will contain 00 vertices. As vertices 88 and 99 only has one descendant leaf, they're always good.