K-th smallest weight on a tree path
Time limit1.5sMemory limit512 MB
Answer each query with the K-th smallest vertex weight on the path between two vertices in a tree.
- Level
Hard8 of 10
- Topics
- Segment tree, Tree, Sorting
- Solved
- No attempts yet
Problem
A tree has N vertices numbered 1 to N and N-1 edges. Each vertex carries one weight. Process M queries on this tree in the order they are given.
A query X Y K asks for the K-th smallest weight among the vertices on the path between vertex X and vertex Y. The path includes both endpoints X and Y.
Input
The first line has two integers N and M. ()
The second line has N integers, the weights of the vertices. The i-th integer is the weight of vertex i. All weights are different, and each one fits in a signed 32-bit integer.
Each of the next N-1 lines has two integers X and Y, meaning vertex X and vertex Y are joined by an edge.
Each of the next M lines has three integers X, Y, and K. X and Y are between 1 and N. K is at least 1 and at most the number of vertices on the path between vertex X and vertex Y. If X and Y are the same, that path holds 1 vertex.
Output
Print one answer per query on its own line, in the order the queries are given.