Doomsday Protocol
Time limit2sMemory limit1024 MB
For each start station and tunnel budget, find the station nearest the shop that the agents can reach using at most k tunnels.
- Level
Medium7 of 10
- Topics
- Tree, Graph, DFS, Binary search
- Solved
- No attempts yet
Statement
Under the Doomsday Protocol, the surviving Kingsman agents must reach a certain wine shop. They may use the London Underground and the secret Kingsman tunnels. The Underground network is a tree, where vertices are stations and edges are the tracks between them. Stations are numbered from to , and the wine shop is at station . All tracks have the same length. Agents may be watched, and moving on the Underground can reveal their location, so they must travel on the Underground only away from the shop. In other words, they can ride from a station to an adjacent one only if the edge distance from the shop to the first station is less than the distance from the shop to the second. Each Kingsman tunnel connects two stations such that one can be reached from the other by moving on the Underground only away from the shop.
Merlin is working through scenarios for activating the Doomsday Protocol. Each scenario is defined by the station where the surviving agents start and the maximum number of Kingsman tunnels they may use. On the Underground they may travel any number of times, but only in the direction away from the shop. For each scenario, Merlin needs the station closest to the shop among those the agents can reach, since they must walk the rest of the way.
Input
The first line contains one integer , the number of stations (). Each of the next lines contains two integers and , the stations connected by an Underground track ().
The next line contains one integer , the total number of Kingsman tunnels (). Each of the next lines contains two integers and , the stations connected by a tunnel (, ). It is guaranteed that one can reach from by moving only away from the shop.
The next line contains one integer , the number of scenarios (). Each of the next lines contains two integers and , the station where the agents start and the number of Kingsman tunnels they may use (, ).
Output
For each scenario, print one integer on its own line: the number of the station closest to the shop among those the agents can reach.