favorite We need a little bit of your help to keep things running, click on this banner to learn more

Shortest paths - interesting graph problems


Between some villages of Vasyuki district there are buses routes. As the passenger traffic is not very large, the buses run only a few times a day.

Maria Ivanovna wants to get from the village d to the village v as soon as possible (it is assumed that at time 0 she is in the village d).


First given the total number of villages n (1n100), d and v, then the number of bus lines r (0r10000). Then given the description of bus trips. Each route is given by the number of the starting village, time of departure, the destination village and the arrival time (all times are integers from 0 to 10000). If at time t the passenger arrives in the village, he can leave it at any time, starting from t.


Print the minimum time when Maria Ivanovna can reach the village v. If she fails with these bus trips to get from d to v, output -1.

Time limit 1 second
Memory limit 128 MiB
Input example #1
1 3
1 0 2 5
1 1 2 3
2 3 3 5
1 1 3 10
Output example #1