This page is still under construction.

Parts of this page are still being built. What you see may change.

Paternity Testing

Time limit3sMemory limit512 MB

Summary
Given a rooted tree, answer queries that sum cnt(i, l, r) over i in [l, r], where cnt counts subtree nodes with labels in a range; queries are encoded online by the previous answer.
Level

Hard8 of 10

Topics
Tree, DFS, Segment tree, Prefix sum
Solved
No attempts yet

Problem

You have a tree of nn nodes labeled 11 through nn. The tree is rooted at node 11. A function cnt(v,l,r)cnt(v, l, r) is the number of nodes in the subtree of node vv whose labels are between ll and rr inclusive. You must answer qq queries. A query is a pair (li,ri)(l_i, r_i). The answer to a query is the sum ∑l≤i≤rcnt(i,l,r)\sum_{l \le i \le r} cnt(i, l, r).

Input

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

The next n−1n - 1 lines give the parent of each node. The ii-th of these n−1n - 1 lines contains the parent of node i+1i + 1.

The following line contains a single integer qq, the number of queries to answer.

Each of the next qq lines contains two numbers uiu_i and viv_i, an encoded query.

Output

Print qq lines. The ii-th line holds the answer to query (li,ri)(l_i, r_i).

Constraints

  • 1≤n≤500001 \le n \le 50000
  • 1≤q≤500001 \le q \le 50000
  • 0≤ui,vi≤1090 \le u_i, v_i \le 10^9

Let ansians_i be the answer to the ii-th query, with ans0=0ans_0 = 0. The parameters of the ii-th query are:

  • xi=1+((ui⊕ansi−1)mod  n)x_i = 1 + ((u_i \oplus ans_{i-1}) \mod n)
  • yi=1+((vi⊕ansi−1)mod  n)y_i = 1 + ((v_i \oplus ans_{i-1}) \mod n)
  • li=min(xi,yi)l_i = min(x_i, y_i)
  • ri=max(xi,yi)r_i = max(x_i, y_i)

Examples1

  1. Example 1

    Input
    9
    1
    2
    3
    4
    5
    5
    7
    8
    5
    0 8
    1 2
    2 3
    4 5
    6 7
    
    Expected output
    42
    8
    3
    3
    3