1676G.md (2728B)
1 Source: https://codeforces.com/problemset/problem/1676/G 2 3 G. White-Black Balanced Subtrees 4 5 time limit per test 6 7 1 second 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 You are given a rooted tree consisting of $n$ vertices numbered from $1$ to $n$. The root is vertex $1$. There is also a string $s$ denoting the color of each vertex: if $s_i = \texttt{B}$, then vertex $i$ is black, and if $s_i = \texttt{W}$, then vertex $i$ is white. 22 23 A subtree of the tree is called balanced if the number of white vertices equals the number of black vertices. Count the number of balanced subtrees. 24 25 A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root. In this problem, all trees have root $1$. 26 27 The tree is specified by an array of parents $a_2, \dots, a_n$ containing $n-1$ numbers: $a_i$ is the parent of the vertex with the number $i$ for all $i = 2, \dots, n$. The parent of a vertex $u$ is a vertex that is the next vertex on a simple path from $u$ to the root. 28 29 The subtree of a vertex $u$ is the set of all vertices that pass through $u$ on a simple path to the root. For example, in the picture below, $7$ is in the subtree of $3$ because the simple path $7 \to 5 \to 3 \to 1$ passes through $3$. Note that a vertex is included in its subtree, and the subtree of the root is the entire tree. 30 31  The picture shows the tree for $n=7$, $a=[1,1,2,3,3,5]$, and $s=\texttt{WBBWWBW}$. The subtree at the vertex $3$ is balanced. 32 33 Input 34 35 The first line of input contains an integer $t$ ($1 \le t \le 10^4$) — the number of test cases. 36 37 The first line of each test case contains an integer $n$ ($2 \le n \le 4000$) — the number of vertices in the tree. 38 39 The second line of each test case contains $n-1$ integers $a_2, \dots, a_n$ ($1 \le a_i \lt i$) — the parents of the vertices $2, \dots, n$. 40 41 The third line of each test case contains a string $s$ of length $n$ consisting of the characters $\texttt{B}$ and $\texttt{W}$ — the coloring of the tree. 42 43 It is guaranteed that the sum of the values $n$ over all test cases does not exceed $2 \cdot 10^5$. 44 45 Output 46 47 For each test case, output a single integer — the number of balanced subtrees. 48 49 Example 50 51 Input 52 53 ``` 54 3 55 56 7 57 58 1 1 2 3 3 5 59 60 WBBWWBW 61 62 2 63 64 1 65 66 BW 67 68 8 69 70 1 2 3 4 5 6 7 71 72 BWBWBWBW 73 ``` 74 75 Output 76 77 ``` 78 2 79 1 80 4 81 ``` 82 83 Note 84 85 The first test case is pictured in the statement. Only the subtrees at vertices $2$ and $3$ are balanced. 86 87 In the second test case, only the subtree at vertex $1$ is balanced. 88 89 In the third test case, only the subtrees at vertices $1$, $3$, $5$, and $7$ are balanced.