#P11006. [2016杭电多校]Born Slippy

[2016杭电多校]Born Slippy

Born Slippy

Problem Description

Professor Zhang has a rooted tree, whose vertices are conveniently labeled by 1,2,...,n1,2,...,n. And the ii-th vertex is assigned with weight wiw_i. For each s{1,2,...,n}s \in \{1,2,...,n\}, Professor Zhang wants find a sequence of vertices v1,v2,...,vmv_1,v_2,...,v_m such that:

  1. v1=sv_1=s and viv_i is the ancestor of vi1v_{i-1} (1<im)(1 < i \le m).
  2. the value $f(s)=w_{v_1}+\sum\limits_{i=2}^{m}w_{v_i} \text{ opt } w_{v_{i-1}}$ is maximum. Operation x opt yx \text{ opt } y denotes bitwise AND, OR or XOR operation of two numbers.

Input

There are multiple test cases. The first line of input contains an integer TT, indicating the number of test cases. For each test case: The first line contains an integer nn and a string optopt $(2 \le n \le 2^{16}, opt \in \{\text{AND}, \text{OR}, \text{XOR}\}$) -- the number of vertices and the operation. The second line contains nn integers w1,w2,...,wnw_1,w_2,...,w_n (0wi<216)(0 \le w_i < 2^{16}). The thrid line contain n1n-1 integers f2,f3,...,fnf_2,f_3,...,f_n (1fi<i)(1 \le f_i < i), where fif_i is the father of vertex ii. There are about 300300 test cases and the sum of nn in all the test cases is no more than 10610^6.

Output

For each test case, output an integer $S=(\sum\limits_{i=1}^{n}{i \cdot f(i)}) \text{ mod } (10^9 + 7)$.

Sample Input

3
5 AND
5 4 3 2 1
1 2 2 4
5 XOR
5 4 3 2 1
1 2 2 4
5 OR
5 4 3 2 1
1 2 2 4

Sample Output

91
139
195

Author

zimpha

Source

2016 Multi-University Training Contest 2