#P13960. [ICPC 2023 Nanjing R] 后缀结构

[ICPC 2023 Nanjing R] 后缀结构

Description

For a string u=u1unu = u_1 \dots u_n, let pre(u,i)\mathrm{pre}(u, i) be the prefix u1uiu_1 \dots u_i. In particular, pre(u,0)\mathrm{pre}(u, 0) is empty string.

For two strings u=u1unu = u_1 \dots u_n and v=v1vmv = v_1 \dots v_m, let u+vu+v be the concatenation u1unv1vmu_1 \dots u_n v_1 \dots v_m.

You are given a string t=t1tmt=t_1 \dots t_m of length mm and a tree TT with (n+1)(n + 1) vertices labeled with 0,1,,n0, 1, \dots, n rooted at vertex 00. Each edge is associated with a character. Please note that in this problem, the alphabet may contain more than 2626 characters.

Consider the following function $$f(i,j) = \max{d(x) \mid s_x\text{ is a suffix of }s_i+ \mathrm{pre}(t,j)}$$ where sis_i be the concatenation of characters on the shortest path from root to vertex ii and d(i)d(i) be the number of edges on the shortest path from the root to vertex ii.

Your task is to compute the values of g1,g2,,gmg_1, g_2, \dots, g_m where gj=i=1nf(i,j)g_j=\sum\limits_{i=1}^{n} f(i,j).

Note that s0s_0 is the empty string and empty string is a suffix of any string.

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 two integers nn and mm (1n,m2×1051 \le n, m \le 2 \times 10^5).

The second line contains nn integers p1,p2,,pnp_1, p_2, \dots, p_n (0pi<i0 \le p_i < i) where pip_i indicates the parent of vertex ii.

The third line contains nn integers c1,c2,,cnc_1, c_2, \dots, c_n (1cin1 \le c_i \le n) where cic_i indicates that the edge from vertex pip_i to vertex ii is associated with the cic_i-th character from the alphabet. It is guaranteed that pipjp_i \ne p_j or cicjc_i \ne c_j for all iji \ne j.

The fourth line contains mm integers t1,t2,,tmt_1, t_2, \dots, t_m (1tin1 \le t_i \le n) where tit_i is the ii-th character of string tt.

It is guaranteed that neither the sum of nn nor the sum of mm will exceed 2×1052 \times 10^5.

Output Format

For each test case output one line containing mm integers g1,g2,,gmg_1, g_2, \dots, g_m separated by a space.

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

2
11 3
0 1 2 0 4 5 4 6 0 9 10
1 3 2 2 1 3 4 1 3 2 1
3 2 4
5 16
0 0 0 1 4
1 2 3 2 2
2 1 3 3 2 1 3 2 1 3 2 2 1 1 2 1
17 26 22
8 5 5 5 5 5 5 5 5 5 5 5 5 5 10 5

Hint

Let's calculate f(11,1)f(11, 1) and f(11,2)f(11, 2) in the first sample test case to help you further understand. We have s11={3,2,1}s_{11} = \{3, 2, 1\} so s11+pre(t,1)={3,2,1,3}s_{11} + \text{pre}(t, 1) = \{3, 2, 1, 3\}. As s6={2,1,3}s_6 = \{2, 1, 3\} is its longest suffix existing in the tree, f(11,1)=d(6)=3f(11, 1) = d(6) = 3. Also s11+pre(t,2)={3,2,1,3,2}s_{11} + \text{pre}(t, 2) = \{3, 2, 1, 3, 2\} and s3={1,3,2}s_3 = \{1, 3, 2\} is its longest suffix existing in the tree, so f(11,2)=d(3)=3f(11, 2) = d(3) = 3.