Cabins
Time limit6sMemory limit64 MB
Find the K-th smallest travel distance among all pairs of cabins placed on a weighted tree of river regions.
- Level
Hard8 of 10
- Topics
- Binary search, Divide and conquer, Tree
- Solved
- No attempts yet
Problem
Subin and Jinyoung were camping by a mountain river when they found cabins. The river has regions. Region 1 sits at the lower course of the river, and the other regions sit at the middle or upper course. The cabins stand in different regions, one cabin per region. In the picture below, the regions painted gray are the ones with a cabin.

From every region except region 1, going down the river brings you to one other region, and the number of that region is always smaller than the number of the region you left. The current is weak, so going down the river takes the same time as going up it. The distance between two regions is the time it takes to travel along the river from one to the other.
A cabin is small, so Subin and Jinyoung cannot stay in the same one. They take two different cabins. While they get along they take the two closest cabins, but after a fight they have to move to the -th closest pair of cabins.
List every pair of two cabins in order of distance, from the smallest, and find the distance of the -th pair.
Input
The first line has the number of regions , the number of cabins , and the relationship value of Subin and Jinyoung.
Each of the next lines, for in this order, has the number of the region you reach by going down the river from region , and the travel time of that stretch.
The last line has the cabin positions in increasing order. Every cabin is in a different region.
, , ,
Output
Print the distance of the -th closest pair of cabins.
Hint
If 3 pairs of cabins are at distance 2 and 2 pairs are at distance 5, then the answers for are 2, 2, 2, 5, 5 in that order.