Top Cluster
Time limit4sMemory limit2048 MB
Given a weighted tree with distinct vertex values, answer queries by finding the smallest value not found within distance k of a given vertex x.
- Level
Hard9 of 10
- Topics
- Divide and conquer, Tree, Binary search
- Solved
- No attempts yet
Problem
Top Cluster is a useful data structure for maintaining data on a tree. Using Top Cluster, we can do range queries efficiently.
Lovely EMmm likes data structure technologies very much. She is learning Top Cluster now, and she is trying to solve a data structure problem. Can you write a program to solve the problem together with EMmm?
In the problem, you will be given a tree with vertices, labeled by . The value of the -th vertex is a non-negative integer . All the values are pairwise distinct.
You will then be given queries. In the -th query, you will be given two integers and (, ), and you need to find the value of .
Here, denotes the length of the shortest path from vertex to vertex . In mathematics, the mex (minimum excluded value) of a set is the smallest non-negative integer that does not belong to the set.
EMmm is good at solving mex problems. She found that when all the values are pairwise distinct, the problem above is equivalent to finding the smallest non-negative integer that either occurred outside the given range, which means , or never occurred in the whole tree. However, she can't go any further. Can you help her solve the problem?
Input
The first line of the input contains two integers and (), the number of vertices and the number of queries.
The second line contains integers (), the values of the vertices. All the values are pairwise distinct.
Each of the next lines contains three integers , and (, , ), describing a two-way edge between vertices and with length . The input forms a tree.
Each of the next lines contains two integers and (, ), describing the -th query.
Output
For each query, print a single line containing the mex value you found.