Tree and Queries 19
Time limit5sMemory limit512 MB
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 vertices is given. A tree is a connected graph with no undirected cycles. The vertices are numbered from to , and each vertex is either black or white.
Write a program that processes the following queries.
- : Flip the color of vertex (white becomes black, and black becomes white). Then, for every pair of distinct white vertices, output the sum of the levels of their LCA (lowest common ancestor).
Vertex is the root. The level of the root is , and the level of any other vertex is the level of its parent plus .
Input
The first line contains and , the number of vertices and the number of queries.
The second line contains integers , the colors of vertices through . means black, and means white.
The third line contains , the parent of each vertex from through .
Each of the next lines contains one query .
Output
The first line contains the answer for the initial state. From the second line on, the next lines each contain the answer for one query.
Constraints
- For ,
- For ,