Little Ivica recently got a job delivering pizzas for the most popular pizzeria in town.
At the start of his workday, he receives a list with the locations to which he needs to deliver pizzas, in order in which the locations are given.
The city is divided into
The pizzeria is in the top left corner
For each location in the city, Ivica knows how much time he will spend every time he is in it (trying to get through the intersection, for example).
Write a program that calculates the smallest amount of time for Ivica to deliver all the pizzas.
Input Specification
The first line contains the integers
The next line contains an integer
Each of the following
Output Specification
Output the smallest amount of time for Ivica to deliver all the pizzas.
Scoring
In test cases worth
Sample Input 1
3 3
1 8 2
2 3 2
1 0 1
3
1 3
3 3
2 2
Sample Output 1
17
Sample Input 2
2 5
0 0 0 0 0
1 4 2 3 2
4
1 5
2 2
2 5
2 1
Sample Output 2
9
In the first example, the shortest path goes through the following locations:
(1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (2, 3), (1, 3), (2, 3), (3, 3), (2, 3) and (2, 2).
The locations in bold show where Mirko made deliveries.
The total time for the deliveries is
Comments