Paternity Testing

아직 제출이 없습니다시간 제한3초메모리 제한512 MB

문제

You have a tree consisting of nn nodes labeled from 11 to nn. The tree is rooted at node 11. A function cnt(v,l,r)cnt(v, l, r) is defined as the number of nodes in a subtree of node vv, that have indices from ll to rr inclusive. You are required to answer qq queries. The query is represented by a pair (l_i,r_i)(l\_i, r\_i). The answer to the query is a sum _lircnt(i,l,r)\sum\_{l \le i \le r} cnt(i, l, r).

입력

First line contains an integer nn --- the number of nodes in the tree.

Next n1n - 1 lines indicate ancestors of the nodes in the tree. Each ii-th line of those n1n - 1 lines contains the ancestor's index for the i+1i + 1-th node in the tree.

The following line contains a single integer qq --- the number of queries to be answered.

Each of the next qq lines contains two numbers u_iu\_i and v_iv\_i --- encoded queries.

출력

Print qq lines. The ii-th line should contain the answer to the query (l_i,r_i)(l\_i, r\_i).

제한

  • 1n500001 \le n \le 50000
  • 1q500001 \le q \le 50000
  • 0u_i,v_i1090 \le u\_i, v\_i \le 10^9

Let ans_ians\_i be the answer to the ii-th query (ans_0=0ans\_0 = 0). Then, the parameters of the  ii-th query are:

  • x_i=1+((u_ians_i1)modn)x\_i = 1 + ((u\_i \oplus ans\_{i-1}) \mod n)
  • y_i=1+((v_ians_i1)modn)y\_i = 1 + ((v\_i \oplus ans\_{i-1}) \mod n)
  • l_i=min(x_i,y_i)l\_i = min(x\_i, y\_i)
  • r_i=max(x_i,y_i)r\_i = max(x\_i, y\_i)