London Underground
Time limit1sMemory limit512 MB
Given subway lines with stop times and a line-change cost, find the minimum travel time between two stations.
- Level
Medium6 of 10
- Topics
- Shortest path, Graph, Dynamic programming
- Solved
- No attempts yet
Problem
The London Underground has stations, numbered 1 to , and lines, numbered 1 to . Each line stops at a fixed sequence of stations and runs back and forth all day. Two consecutive stations on a line are the same distance apart in both directions, and a train leaves every station in both directions every minute, so waiting for a train takes no time.
A line is given as its stops in order, and each stop carries the number of minutes from the start of the line to that station. Riding one line from one of its stops to another takes the difference between those two numbers.
You can change from line to line at station when both lines stop at , and one change takes minutes. Boarding the first line at the start of the trip and leaving the last line at the end take no time.
Alice and Bob are visiting London. They ride the underground a lot, and they keep feeling that they are not always taking the fastest route. Find the shortest travel time from station to station .
Input
The first line has one integer , the number of test cases.
Each test case begins with a line of five integers , , , , , separated by spaces. They give the number of minutes one line change takes, the number of stations, the number of lines, the start station, and the end station.
The next lines describe the subway lines. Each of those lines begins with an integer , the number of stops on that subway line, followed by stop specifications separated by spaces, in the order the stops appear along the line. A stop specification is two integers, where the first number is the station number and the second number is the number of minutes from the start of the line to that station.
- and
- for every line
- for every line
- for every line
- for every line
- Every station from 1 to is on at least one line.
- Every station is reachable from every other station.
Output
For each test case, print on its own line the smallest number of minutes needed to travel from station to station .