Under construction

Still being built. Things may change

Tree and Queries 19

Time limit5sMemory limit512 MB

Summary
Each query flips the color of vertex X, then asks for the sum of LCA levels over all pairs of white vertices in the tree.
Level

Medium7 of 10

Topics
Tree, Segment tree, Math
Solved
No attempts yet

Problem

A tree with NN vertices is given. A tree is a connected graph with no undirected cycles. The vertices are numbered from 11 to NN, and each vertex is either black or white.

Write a program that processes the following queries.

  • XX: Flip the color of vertex XX (white becomes black, and black becomes white). Then, for every pair (a,b)(a, b) of distinct white vertices, output the sum of the levels of their LCA (lowest common ancestor).

Vertex 11 is the root. The level of the root is 00, and the level of any other vertex is the level of its parent plus 11.

Input

The first line contains NN and QQ, the number of vertices and the number of queries.

The second line contains integers t1,t2,⋯ ,tNt_1, t_2, \cdots, t_N, the colors of vertices 11 through NN. ti=0t_i = 0 means black, and ti=1t_i = 1 means white.

The third line contains P2,P3,⋯ ,PNP_2, P_3, \cdots, P_N, the parent of each vertex from 22 through NN.

Each of the next QQ lines contains one query XX.

Output

The first line contains the answer for the initial state. From the second line on, the next QQ lines each contain the answer for one query.

Constraints

  • 2≤N≤5×1052 \le N \le 5 \times 10^5
  • 1≤Q≤5×1051 \le Q \le 5 \times 10^5
  • For 1≤i≤N1 \le i \le N, 0≤ti≤10 \le t_i \le 1
  • For 2≤i≤N2 \le i \le N, 1≤Pi<i1 \le P_i < i
  • 1≤X≤N1 \le X \le N

Examples3

  1. Example 1

    Input
    5 5
    1 0 0 1 1
    1 1 3 2
    5
    3
    5
    4
    2
    
    Expected output
    0
    0
    1
    1
    0
    1
    
  2. Example 2

    Input
    10 10
    1 0 0 1 1 0 1 0 1 0
    1 2 1 4 5 6 1 4 1
    8
    4
    4
    4
    10
    9
    2
    1
    5
    3
    
    Expected output
    7
    7
    4
    7
    4
    4
    2
    2
    2
    0
    1
    
  3. Example 3

    Input
    20 20
    1 0 1 0 1 0 0 1 1 0 0 0 0 1 0 0 0 1 1 0
    1 2 3 4 2 2 1 3 2 4 4 3 3 3 8 14 11 7 7
    5
    12
    19
    5
    10
    18
    17
    13
    10
    5
    5
    13
    10
    4
    11
    8
    14
    13
    19
    15
    
    Expected output
    26
    16
    26
    21
    33
    39
    26
    38
    51
    44
    31
    44
    32
    38
    53
    71
    71
    55
    70
    79
    97