Finding the Ship
Time limit3sMemory limit1024 MB
Given a graph and queries (v, k), find the single point the ship must occupy after k steps on a shortest path from s to v, or report impossible or ambiguous.
- Level
Medium7 of 10
- Topics
- BFS, Graph, Shortest path, Tree
- Solved
- No attempts yet
Problem
The Guardians of the Galaxy received a distress signal from a ship that Thanos destroyed. They must find the ship as soon as possible and rescue Thor, who is on board.
The ship moves in an unusual way. There are distinct points in the universe, numbered from 1 to , and the ship moves between them. There are also wormholes, where the -th wormhole connects points and . A wormhole may connect a point to itself, and two points may be connected by more than one wormhole. Traveling through any single wormhole takes exactly one hour.
Initially the ship is at point . The Guardians think Thor tried to steer the ship toward one of the points but had to stop along the way. They have guesses. In the -th guess, Thor started at point and followed one of the shortest paths to point . After passing through wormholes times, the ship stopped and did not move any further. A shortest path is a path that uses the smallest possible number of wormholes.
Input
The first line contains three integers , , and , the number of points, the number of wormholes, and the starting point (; ).
Each of the next lines contains two integers and , the points joined by the -th wormhole ().
The next line contains a single integer , the number of guesses ().
Each of the next lines contains two integers and , the guessed destination and the number of wormholes Thor passed through (; ).
Output
For each guess, print one line with one of the following results.
- If the situation in the guess is impossible (for example, there is no path from to ), print .
- If the situation is possible and more than one point could hold the ship at that moment, print .
- Otherwise, print the number of the single point where the ship must be according to the guess.