Island Trip
InterviewTime limit1sMemory limit256 MB
Given an undirected graph with node heights, for each query (A, K) find the minimum height reachable from A in exactly K edge steps, or -1 if impossible.
- Level
Medium6 of 10
- Topics
- Graph, Dynamic programming, BFS, Matrix
- Solved
- No attempts yet
Problem
Jeongwoo travels for a living and for fun, and this time he plans to tour a group of islands. He picked islands, and bridges connect them, each bridge passable in both directions. Crossing one bridge counts as one move.
While reading the island heights printed on his map, Jeongwoo started wondering:
"Starting from island and crossing exactly bridges, what is the lowest height among the islands I can end up on?"
The same bridge may be crossed several times, and an island already visited may be visited again. Answer each of Jeongwoo's queries.
Input
The first line contains the number of islands and the number of bridges , separated by a space. (, )
The second line contains the heights of islands 1 through , separated by spaces. ()
Each of the next lines contains two integers and describing one bridge, separated by a space. () It means island and island are joined by a bridge passable in both directions. and may be equal, and the same pair of islands may appear on several lines.
The next line contains the number of queries . ()
Each of the following lines contains the starting island and the number of bridges to cross , separated by a space. (, )
Output
For each query, print on its own line the lowest height among the islands reachable from island by crossing exactly bridges.
If no island is reachable with exactly crossings, print .