Stablo

시간 제한2초메모리 제한2048 MB

요약
노드 x를 y 아래로 옮긴 뒤, y의 서브트리에 속한 모든 노드에서 y까지의 가중 거리 합을 구한다.
난이도

어려움10점 중 9점

유형
트리, DFS, 누적 합, 동적 계획법
정답자
아직 제출이 없습니다

문제

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 NN nodes, where the root of the tree is node 11. Each node has an associated value v\[i]v\[i]. The structure of the tree is defined using an array p\[i]p\[i], where for each ii from 11 to N−1N - 1, p\[i]p\[i] denotes the parent of i+1i + 1.

A function f(y)f(y) is defined for a node yy in the tree as:

f(y)=∑_x∈S_yd(x,y)⋅v\[x]f(y) = \sum\_{x \in S\_y}{d(x, y) \cdot v\[x]}

where d(x,y)d(x, y) denotes the distance between nodes xx and yy, while S_yS\_y contains all nodes for which yy is an ancestor.

You are given QQ queries with two nodes xx and yy. For each query, the following transformation must be simulated in the tree, and the function f(y)f(y) needs to be calculated:

  1. Attach all nodes for which xx is the parent to the parent of xx
  2. Remove xx from the tree
  3. Insert node xx back into the tree, between yy and the descendant of yy from whose subtree xx was removed.

If yy is the parent of xx, the tree remains unchanged. It is always true that xx is in the subtree of yy. For each query, the value of f(y)f(y) 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 NN and QQ (1≤N,Q≤5⋅1051 ≤ N, Q ≤ 5 \cdot 10^5), the number of nodes in the tree and the number of queries, respectively.

The second line contains NN integers v\[i]v\[i] (1≤v\[i]≤1061 ≤ v\[i] ≤ 10^6), representing the value of each node.

The third line contains N−1N - 1 integers p\[i]p\[i] (1≤p\[i]≤i1 ≤ p\[i] ≤ i), where p\[i]p\[i] denotes the parent of node i+1i + 1.

Each of the next QQ lines contains two integers xx and yy (1≤x,y≤N1 ≤ x, y ≤ N), denoting the nodes involved in the operation described above.

출력

In the next QQ lines output the value of the function f(y)f(y) on the modified tree.

힌트

Clarification of the first example: After applying the operation on a tree, node 33 is at a distance of 11 from node 11, and node 22 is at a distance of 22 from node 11. The result is 3+2⋅2=73 + 2 \cdot 2 = 7.

예제3

  1. 예제 1

    입력
    3 1
    1 2 3
    1 2
    3 1
    
    예상 출력
    7
    
  2. 예제 2

    입력
    3 2
    4 5 6
    1 1
    2 1
    3 1
    
    예상 출력
    11
    11
    
  3. 예제 3

    입력
    5 3
    2 5 2 2 2
    1 2 3 2
    4 3
    3 2
    5 1
    
    예상 출력
    2
    8
    26