Taking the Metro (Large)
Time limit5sMemory limit512 MB
Find the fastest route between two metro stations where each boarding adds a line waiting time and transfers use walking tunnels.
- Level
Medium5 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
Tom rides the city metro to get from one station to another.
The metro system works like this.
- The city has metro lines, numbered 1 to .
- Line has stations, written in order from one end of the line to the other. Trains run in both directions, so a train goes and another goes . You can board at any station and get off at any station. Riding from to takes minutes, and the same ride in the opposite direction takes the same time.
- There are transfer tunnels. Each tunnel connects two stations that belong to different lines, and walking through it takes the same time in either direction. You get off a train at one end of a tunnel, walk through the tunnel, and arrive at the station at the other end.
- Every time you board a train of line , you wait minutes for that train. Staying on a train while it passes a station costs no extra time, and getting off costs no time.
You start at one station and travel to another one. Find the shortest total time.
Input
The first line holds the number of test cases . The test cases follow.
Each test case starts with a line holding , the number of metro lines. Descriptions of the lines follow. The description of line starts with a line holding two integers and , the number of stations and the waiting time in minutes. The next line holds integers , the riding times between neighboring stations.
After the line descriptions comes a line holding , the number of transfer tunnels, then lines. Each of them holds five integers , , , , , meaning that a tunnel connects station and station , and that walking through that tunnel takes minutes.
The next line holds , the number of queries, followed by lines. Each of them holds four integers , , , , meaning that you travel from station to station .
Limits:
- , and one test case has at most 1000 stations in total
- , , , , and
- , , ,
- Station and station are different
Output
For each test case, print one line holding Case #x:, where x is the test case number starting from 1. Then print lines. The -th of them holds the shortest time for the -th query, or -1 when the destination cannot be reached.
Hint
In the first query of the first test case of the sample input you go from station 1 of line 1 to station 4 of line 2. One shortest route is:
- Wait 3 minutes for a train of line 1 and board it.
- Ride 3 minutes and get off at station 2.
- Walk the tunnel for 1 minute to station 2 of line 2.
- Wait 2 minutes for a train of line 2 and board it.
- Ride 2 minutes and get off at station 4.
The total time is 3 + 3 + 1 + 2 + 2 = 11.