#P5399. [Ynoi2018] 駄作

[Ynoi2018] 駄作

Description

Caicaizi gives you a tree with nn nodes, numbered from 11 to nn.

Define the distance d(a,b)d(a,b) between two nodes a,ba,b on the tree as the smallest non-negative integer kk such that there exists a node sequence v0,v1,...,vkv_0,v_1,...,v_k with v0=a,vk=bv_0=a,v_k=b, and for 0ik10\leq i\leq k-1, there is an edge connecting viv_i and vi+1v_{i+1} in the tree.

There are mm queries. Each query contains parameters p0,d0,p1,d1p_0,d_0,p_1,d_1. Compute:

$$\sum\limits_{d(p_0,a)\leq d_0}\sum\limits_{d(p_1,b)\leq d_1}d(a,b)$$

Input Format

The first line contains an integer nn, representing the number of nodes in the tree.

The next line contains n1n-1 integers f2,f3,...,fnf_2,f_3,...,f_n, which indicate that there is an edge between ii and fif_i (1fii11\leq f_i\leq i-1).

The next line contains an integer mm, representing the number of queries.

The next mm lines describe all queries. Each line contains four integers p0,d0,p1,d1p_0,d_0,p_1,d_1 (1p0,p1n,0d0,d1n11\leq p_0,p_1\leq n,0\leq d_0,d_1\leq n-1), describing one query.

Output Format

Output mm lines, answering the queries in order. Each line outputs one integer, which is the answer to that query.

7
1 1 2 3 5 2
5
5 1 5 0
2 0 5 0
2 2 4 5
7 2 2 4
3 2 5 4

2
3
69
57
70

Hint

Idea: nzhtl1477, Solution: ccz181078, Code: ccz181078, Data: ccz181078

Constraints: for 100%100\% of the data, 1n1051\leq n\leq 10^5 and 1m1051\leq m\leq 10^5.

Translated by ChatGPT 5