#BS0000423. Đến đúng giờ (Arriving on Time)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Đến đúng giờ (Arriving on Time)
Arriving on Time
Source: Kattis
Version: Phuoc Hung OJ Extended
Problem Statement
You are working at a hotel in Zürich before a meeting. You must reach the meeting venue by time , but wish to remain at the hotel as long as possible. All times are measured in seconds from the present, time .
The city has tram stops numbered through . The hotel is at stop and the meeting venue is at stop .
A tram line runs from stop to stop . Its first departure is at , with subsequent departures spaced seconds apart. Each ride takes exactly seconds. Thus departures occur at .
You may wait at a stop. Transfers take no time, so arriving exactly when another tram departs allows you to board it. Find the latest integer time to leave the hotel and still reach the venue no later than .
Input
The first line contains integers , the numbers of stops and lines and the meeting deadline.
Each of the next lines contains five integers : departure stop, arrival stop, first departure time, departure interval, and ride duration, in seconds where applicable.
Output
Print the latest departure time from the hotel as an integer in seconds from now. If timely arrival is impossible even when leaving at time , print impossible.
Subtasks
- Subtask 1 (20 points): ; ; ; , ; ; . Each line travels only from to .
- Subtask 2 (30 points): ; ; ; , ; ; . Each line travels only from to .
- Subtask 3 (50 points): ; ; ; , ; ; . Each line travels only from to .
Examples
Input
2 1 10
0 1 1 2 6
Output
3
Explanation
The meeting starts at second 10. Trams from 0 to 1 depart at 1, 3, 5, ... and take 6 seconds. The departure at 3 arrives at 9; the next at 5 arrives at 11, too late. Hence 3 is the latest hotel departure.
Input
2 1 5
0 1 1 1 5
Output
impossible
Explanation
The deadline is 5. The earliest tram departs at 1 and takes 5 seconds, reaching the venue at 6. No trip meets the deadline.
Input
3 3 12
0 1 0 3 2
1 2 2 4 2
0 2 0 1 10
Output
6
Explanation
Leave at 6, reach stop 1 at 8, wait until 10, and reach stop 2 at exactly 12. Leaving after 6 means the first available ride to stop 1 departs at 9 and arrives at 11, missing the departure at 10. The direct line takes 10 seconds and requires leaving by 2. Thus 6 is optimal.