Taking Metro (Small)
Time limit5sMemory limit512 MB
Find the fastest route between two metro stations, combining per-line boarding waits, ride times, and tunnel walks.
- Level
Medium4 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
Tom rides the metro to get from one station to another.
The metro system works like this.
- The city has metro lines: line 1, line 2, ..., line .
- Line has stations, listed from one terminus to the other as . Trains run in both directions, that is and . You can board at any station and get off at any station. Travelling between two neighbouring stations takes time: minutes from to , minutes from to , and so on. The other direction takes the same time.
- There are transfer tunnels. Each tunnel connects two stations of two different lines. Walking through a tunnel takes a fixed time, the same in either direction. You can get off at the station on one end of a tunnel and walk to the station on the other end.
- To board a train at a station of line you have to wait minutes. This also applies to the first train you board, at the starting station.
You are going to travel from one station to another. Find the smallest possible time.
Input
The first line contains the number of test cases, . test cases follow.
Each test case starts with a line containing the number of metro lines, . Descriptions of lines follow. Each line description starts with a row holding the number of stations and the waiting time . The next row holds integers , the travel times between neighbouring stations.
After the line descriptions comes a row holding the number of tunnels, . Each of the next rows holds 5 integers , , , , : the tunnel connects station and station , and walking through it takes minutes.
The next row holds the number of queries, . Each of the next rows holds 4 integers , , , , meaning you travel from station to station .
Limits
- The total number of stations in one test case is at most 100.
- ,
- ,
- and are different.
- ,
- ,
- Station and station are different.
Output
For each test case, first print Case #x:, where x is the test case number starting from 1. Then print lines, one per query in the order given. Each line holds the smallest time for that query as an integer, or -1 if the trip is impossible.
Note
In the first test case of the first example you travel from station 1 of line 1 to station 4 of line 2. The fastest way is:
- wait 3 minutes for a train on line 1 and board it,
- ride for 3 minutes and get off at station 2,
- walk through the tunnel for 1 minute to station 2 of line 2,
- wait 2 minutes for a train on line 2 and board it,
- ride for 2 minutes and get off at station 4.
The time spent is minutes.