Paternity Testing
Time limit3sMemory limit512 MB
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 nodes labeled through . The tree is rooted at node . A function is the number of nodes in the subtree of node whose labels are between and inclusive. You must answer queries. A query is a pair . The answer to a query is the sum .
Input
The first line contains an integer , the number of nodes in the tree.
The next lines give the parent of each node. The -th of these lines contains the parent of node .
The following line contains a single integer , the number of queries to answer.
Each of the next lines contains two numbers and , an encoded query.
Output
Print lines. The -th line holds the answer to query .
Constraints
Let be the answer to the -th query, with . The parameters of the -th query are: