#P5374. [THUPC 2019] 不用找的树

[THUPC 2019] 不用找的树

Description

You are given 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=av_0=a, vk=bv_k=b, and for every 0ik10\leq i\leq k-1, there is an edge directly 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, the number of nodes in the tree.

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

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

The next mm lines describe the 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.

Constraints: 1n105,1m1051\leq n\leq 10^5,1\leq m\leq 10^5.

Output Format

Output mm lines. For each query, output one integer on its own line, 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

From THUPC (THU Programming Contest, Tsinghua University Programming Contest) 2019.

Resources such as editorials can be found at https://github.com/wangyurzee7/THUPC2019.

Translated by ChatGPT 5