#P12861. [NERC 2020 Online] Lookup Performance
[NERC 2020 Online] Lookup Performance
题目描述
A is a rooted binary tree whose nodes store keys so that each node's key is greater than all the keys in the node's left subtree and less than those in its right subtree.
A binary search tree can be used to maintain sorted sets and allows to perform different types of queries on the set. A query that we are considering in this problem is finding the number of values in the range within the set.
Let be the set of all keys in the binary search tree. You are given two values and . The query is to find the number of such so that . The following recursive function computes this value when called with the parameters , where is the root of the binary search tree.
function lookup(v, L, R):
if v == null:
return 0
if L <= v.min and v.max <= R:
return v.count
if v.max < L or R < v.min:
return 0
res = 0
if L <= v.key and v.key <= R:
res += 1
res += lookup(v.left, L, R)
res += lookup(v.right, L, R)
return res
Values $\verb|v.left|, \verb|v.right|, \verb|v.min|, \verb|v.max|, \verb|v.key|$, and are the fields of the nodes of the binary search tree.
- and are the left and the right children of node , respectively.
- and are the minimum and the maximum keys in the subtree rooted at node .
- is the key of node .
- is the number of nodes in the subtree rooted at node .
You are given a binary search tree with integer keys. You are also given queries, each query consisting of two integers and . Find the number of calls of the function that are made when is called, including the initial call itself.
输入格式
The first line contains an integer () --- the number of nodes in the binary search tree.
The next lines describe the nodes of the tree. The -th of these lines contains three integers , , and denoting the left child, the right child and the key of the -th node. If the node does not have the left or/and the right child, the corresponding value is 0 ( or ; or ; ). The root of the tree is at node 1 and it is guaranteed to be a well-formed binary search tree.
Note that the values and are not given in the input explicitly, since they can be deduced from , and .
The next line contains an integer () --- the number of the queries.
Each of the next lines contains two integers and () --- the parameters given to the function.
输出格式
Output lines, the -th line containing a single integer --- the number of calls of the function that are made for the -th query.
7
2 3 4
4 0 2
5 6 8
0 0 1
0 7 5
0 0 9
0 0 6
5
2 7
0 10
2 8
4 4
3 3
7
1
7
3
3