atcoder#ABC192E. [ABC192E] Train
[ABC192E] Train
Score : points
Problem Statement
In the Republic of AtCoder, there are cities numbered through and railroads numbered through .
Railroad connects City and City bidirectionally. At time , , and all subsequent multiples of , a train departs from each of these cities and head to the other city. The time each of these trains takes to reach the destination is .
You are now at City . Find the earliest time you can reach City when you start the journey by taking a train that departs City not earlier than time . If City is unreachable, report that fact. The time it takes to transfer is ignorable. That is, at every city, you can transfer to a train that departs at the exact time your train arrives at that city.
Constraints
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the earliest possible time you can reach City . If City is unreachable, print -1
instead.
3 2 1 3
1 2 2 3
2 3 3 4
7
First, you take Railroad at time and go from City to City . You arrive at City at time .
Then, you take Railroad at time and go from City to City . You arrive at City at time .
There is no way to reach City earlier.
3 2 3 1
1 2 2 3
2 3 3 4
5
First, you take Railroad at time and go from City to City . You arrive at City at time .
Then, you take Railroad at time and go from City to City . You arrive at City at time .
3 0 3 1
-1
9 14 6 7
3 1 4 1
5 9 2 6
5 3 5 8
9 7 9 3
2 3 8 4
6 2 6 4
3 8 3 2
7 9 5 2
8 4 1 9
7 1 6 9
3 9 9 3
7 5 1 5
8 2 9 7
4 9 4 4
26