Stablo
시간 제한2초메모리 제한2048 MB
노드 x를 y 아래로 옮긴 뒤, y의 서브트리에 속한 모든 노드에서 y까지의 가중 거리 합을 구한다.
문제
Toni decided to create a task for HONI (and COCI). Since he doesn’t like kids, he decided to make the task as difficult as possible. He came up with a complex problem involving a tree that constantly changes, solely to make contestants suffer as much as possible.
You are given a weightless tree with nodes, where the root of the tree is node . Each node has an associated value . The structure of the tree is defined using an array , where for each from to , denotes the parent of .
A function is defined for a node in the tree as:
where denotes the distance between nodes and , while contains all nodes for which is an ancestor.
You are given queries with two nodes and . For each query, the following transformation must be simulated in the tree, and the function needs to be calculated:
- Attach all nodes for which is the parent to the parent of
- Remove from the tree
- Insert node back into the tree, between and the descendant of from whose subtree was removed.
If is the parent of , the tree remains unchanged. It is always true that is in the subtree of . For each query, the value of must be calculated after the tree is temporarily modified according to the procedure described above. The tree modifications are not permanent, i.e. after each query, the tree returns to its original state.
입력
The first line contains two integers and (), the number of nodes in the tree and the number of queries, respectively.
The second line contains integers (), representing the value of each node.
The third line contains integers (), where denotes the parent of node .
Each of the next lines contains two integers and (), denoting the nodes involved in the operation described above.
출력
In the next lines output the value of the function on the modified tree.
힌트
Clarification of the first example: After applying the operation on a tree, node is at a distance of from node , and node is at a distance of from node . The result is .