#abc232g. [abc232_g]Modulo Shortest Path
[abc232_g]Modulo Shortest Path
Problem Statement
We have a directed graph with vertices, called Vertex , Vertex , , Vertex .
For each pair of integers such that and , there is a directed edge from Vertex to Vertex of weight . (Here, denotes the remainder when is divided by .)
There is no edge other than the above.
Print the shortest distance from Vertex to Vertex , that is, the minimum possible total weight of the edges in a path from Vertex to Vertex .
Constraints
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print the minimum possible total weight of the edges in a path from Vertex to Vertex .
Sample Input 1
4 12
10 11 6 0
8 7 4 1
Sample Output 1
3
Below, denotes the directed edge from Vertex to Vertex .
Let us consider the path .
- Edge weighs ,
- Edge weighs ,
- Edge weighs .
Thus, the total weight of the edges in this path is .
This is the minimum possible sum for a path from Vertex to Vertex .
Sample Input 2
10 1000
785 934 671 520 794 168 586 667 411 332
363 763 40 425 524 311 139 875 548 198
Sample Output 2
462