Crosswalk
Time limit1sMemory limit1024 MB
Given a cyclic schedule of crosswalks that each turn green for one minute per cycle, find the earliest arrival time from area 1 to area N.
- Level
Medium7 of 10
- Topics
- Graph, Shortest path, BFS, Math
- Solved
- No attempts yet
Problem
On your way home you have come across a busy intersection. This intersection has areas that people can pass through, and several crosswalks connecting these areas. Every area is connected to every other, directly or indirectly, through crosswalks. For convenience, number the areas from to .

You analyzed the intersection's signals from afar, so you know the order in which the crosswalks get a green light. A signal cycle lasts minutes, and the signal changes every minute. The -th signal of each cycle () starts at minutes and for minute gives a green light to the crosswalk connecting area and area , while every other crosswalk gets a red light. The same crosswalk can get a green light several times within one cycle.
When a crosswalk has a green light, you can use it to move to the area on the other side, and the move takes minute. The signal must not turn red while you are crossing, so if the signal is green during time , you must start crossing the crosswalk during time .
Given the crosswalks and the signal information, write a program that finds the minimum time needed to get from area to area , starting at minute .
Input
The first line gives the number of areas and the signal cycle length , separated by a space.
Of the lines starting from the second line, the -th line gives the two endpoints and of the crosswalk that gets a green light for minute starting at minutes , separated by a space.
Output
On the first line, print the minimum time in minutes needed to get from area to area .
Constraints
- Every area is connected to every other, directly or indirectly, through crosswalks.
- All numbers in the input are integers.