K-th smallest weight on a tree path
Time limit2sMemory limit512 MB
For each query, print the k-th smallest vertex weight on the unique tree path between two vertices.
- Level
Hard8 of 10
- Topics
- Tree, Binary search, Prefix sum, Implementation
- Solved
- No attempts yet
Problem
You are given a tree with vertices. A tree is a connected undirected graph with no cycle. Vertices are numbered from 1 to , edges are numbered from 1 to , and every vertex carries one weight.
Write a program that answers the following query.
u v k: print the -th smallest weight among the weights of the vertices on the path from vertex to vertex .
A tree has exactly one path between two vertices, and that path includes both endpoints and . Equal weights on different vertices are counted separately when ranking. If the weights on the path are 3, 7, 7, 9, then both the 2nd smallest and the 3rd smallest value are 7.
Input
The first line contains the number of vertices . ()
The second line contains the weights of vertex 1 through vertex in order. Each weight is a natural number not greater than .
Each of the next lines contains two vertex numbers and joined by edge .
The next line contains the number of queries . ()
Each of the next lines contains one query in the form u v k. Both and are vertex numbers and they may be equal. is a natural number not greater than the number of vertices on the path from to .
Output
Print the answer to each query on its own line, in the order the queries are given.