Matrix
InterviewTime limit2sMemory limit256 MB
Compute each agent's earliest arrival time, then find Neo's shortest safe route to a telephone that beats every agent there.
- Level
Medium5 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
After years of searching, Morpheus found The One: a computer programmer named Thomas A. Anderson, known to his friends as Neo. On the way back from the Oracle, Morpheus reached the real world first, and an agent destroyed the telephone before Neo could pick it up. Neo has not reached his full potential yet, so he has to run to another telephone without fighting an agent.
The Matrix world has locations, and Neo stands at location . There are paths connecting locations. Every path is bidirectional and takes a fixed amount of time to walk. You know where the agents are and where the telephones are.
You do not know how the agents move, so assume the worst case. If some agent can reach location in minutes at the earliest, then from time on there may be an agent standing at . Neo may therefore pass only through locations he reaches strictly before . Arriving exactly at time counts as meeting an agent. The same rule applies to a location that holds a telephone: if Neo and an agent reach the telephone at the same time, Neo has to fight the agent before picking up the phone.
Neo starts at location at time and never stops on the way. If he can reach some telephone safely, report the earliest arrival time among those telephones. If he cannot reach any telephone safely, report that instead.
Input
The first line contains the number of test cases ().
The first line of each test case contains four integers , , , : the number of locations, the number of paths, the number of agents, and the number of telephones. (, , , , )
Each of the next lines contains three integers , , (, ), meaning that a path connects location and location and takes minutes to walk. Several paths may connect the same pair of locations, and may equal .
The next line contains the locations of the agents.
The last line contains the locations of the telephones.
Location holds no agent and no telephone. No location holds both an agent and a telephone. The sum of over all test cases is at most , and the sum of is at most .
Output
Print one line per test case. If no telephone can be reached safely, print Neo may fight an Agent. Otherwise print the minimum time in minutes needed to get out of the Matrix, as an integer.