We can model a rail network as a directed graph, where each node is a train station and each edge is a train connecting two train stations. We'll assume that each train travels between its corresponding stations at a regular schedule and takes a fixed amount of time
Your code should take a list of trains, where each train is a tuple (from, to, base, interval, duration)
, where
from
is an integer denoting the station the train departs from.to
is an integer denoting the station the train arrives at.base
is the integer timestamp of an arbitrary departure of the given train.interval
is a positive integer denoting how often the train departs.duration
a positive integer denoting how long the train takes.
In other words, the departures are given by base + n * interval
, and the corresponding arrivals by base + n * interval + duration
, for integer n
.
For example, 0 2 -3 4 5
would describe a train going from station 0
to station 2
, which is at station 0
at times ..., -11, -7, -3, 1, 5, 9, 13, ...
and is at station 2
at times ..., -6, -2, 2, 6, 10, 14, 18, ...
.
If you are at some station x
want to take a train from x
to y
, you must wait until the train from x
to y
is at station x
. Then, after another duration
units of time, you are at station y
.
For example, if at time 0
you're at station 0
and want to use the train described above, you'd need to wait until time 1
, then at time 6
you would be at station 2
.
Given these trains, your code should calculate the earliest arrival time at station 1
, given that you start at station 0
at time 0
. If no route is possible, you should return a distinguished value.
Worked Example
Suppose we are given input:
0 2 -3 4 5
2 1 9 3 2
0 1 -1 7 9
From this, we can see the pairs of arrival and departure times of each train are:
..., (1, 6), (5, 10), (9, 14), (13, 18), (17, 22), (21, 26), (25, 30), ...
..., (0, 2), (3, 5), (6, 8), (9, 11), (12, 14), (15, 17), (18, 20), ...
..., (6, 15), (13, 22), (20, 29), (27, 36), (34, 43), (41, 50), (48, 57), ...
There are 2 routes from stations 0
to 1
: 0 -> 1
and 0 -> 2 -> 1
.
- For the route
0 -> 1
, we can board the train at time6
and get off at time15
. - For the route
0 -> 2 -> 1
, we can get on train0 -> 2
at time1
, arrive at station2
at time6
, then immediately board train2 -> 1
, arriving at station1
at time8
.
Out of these, 0 -> 2 -> 1
is the fastest, so we output 8
.