Buses
Time limit1sMemory limit128 MB
Given bus timetables at every stop, pick an outbound bus and an inbound bus to minimize John's total waiting time before his friend arrives, returning by the friend's arrival time.
- Level
Medium7 of 10
- Topics
- Sorting, Binary search, Array, Implementation
- Solved
- No attempts yet
Problem
John arrives at a bus depot early to meet a friend. The friend will arrive later, and it is cold outside, so instead of waiting the whole time John wants to ride a bus a few stops down the route and take another bus back to the depot before his friend shows up.
He wants to minimize the total time he spends waiting, which is the sum of three parts:
- the time he waits at the depot before boarding the outbound bus,
- the time he waits to change buses at the stop where he turns around, and
- the time he waits for his friend after returning to the depot.
John is punctual and must not be late: he has to be back at the depot no later than his friend's arrival time. Write a program that reads the arrival times and the bus timetable and prints the shortest possible total waiting time.
Input
The first line contains five integers , , , , separated by single spaces, where , , , and :
- : the moment John arrives at the depot,
- : the moment his friend arrives at the depot,
- : the number of stops on the route, including the depot,
- : the number of buses that depart from the depot,
- : the number of buses that arrive at the depot.
The next lines give the timetable, one line per stop, in order: stop is the depot, then stops . Outbound buses run ; inbound buses run . Each stop's line has integers with : the first values are the times of the outbound buses at that stop, and the remaining values are the times of the inbound buses at that stop.
Every bus needs at least one time unit to travel between two consecutive stops. John boards a bus at a stop only if he is present at that bus's time for the stop. Changing from one bus to another at a stop, where the two buses are there at times and , is possible only if .
Output
Print a single integer: the minimum total time John has to spend waiting. If no pair of buses lets him make the round trip and return by his friend's arrival, he waits at the depot the whole time, so the answer is .
Note
In the example, the optimal plan is: board the outbound bus at the depot at time , get off at stop , board the inbound bus at time , and arrive back at the depot at time . The waiting time is at the depot, to change buses, and for the friend, which is in total.