There are
For each bus route
The traveler does not like waiting, and therefore is looking for a travel plan which minimizes the maximal possible waiting time while still guaranteeing that he'll not miss connecting buses (that is, every time he changes buses, the latest possible arrival of the incoming bus must not be later than the earliest possible departure time of the outgoing bus).
When counting waiting time we have to assume the earliest possible arrival time and the latest possible departure time.
Write a program to help the traveler to find a suitable plan.
Input Specification
The first line contains the integer numbers
The following
Output Specification
The only line of the output should contain the maximal possible total
waiting time for the most suitable possible travel plan. If it is not possible to guarantee
arrival in town -1
.
Sample Input 1
3 6 2 100
1 3 10 20 30 40
3 2 32 35 95 95
1 1 1 1 7 8
1 3 8 8 9 9
2 2 98 98 99 99
1 2 0 0 99 101
Sample Output 1
32
The most pessimistic case for the optimal travel plan for the above example is as follows:
Time | Action |
---|---|
0...1 | Wait in town 1 |
1...7 | Take the bus line 3 from town 1 to town 1 |
7...8 | Wait in town 1 |
8...9 | Take the bus line 4 from town 1 to town 3 |
9...35 | Wait in town 3 |
35...95 | Take the bus line 2 from town 3 to town 2 |
95...98 | Wait in town 2 |
98...99 | Take the bus line 5 from town 2 to town 2 |
99...100 | Wait in town 2 |
Total waiting time:
Sample Input 2
3 2 2 100
1 3 0 0 49 51
3 2 50 51 100 100
Sample Output 2
-1
Comments