Driving license test
Time limit2sMemory limit256 MB
Move only right and down from the top left corner to the bottom right corner with at most G fuel to arrive as early as possible.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Graph
- Solved
- No attempts yet
Problem
A driving license test is held on a course laid out as a grid with rows and columns.

The test has three rules.
- Rule 1: The candidate starts at the top left point s and drives east (right) and south (down) only, until reaching the bottom right point t.
- Rule 2: Driving one grid segment straight takes time , the same going right and going down. is a constant fixed before the test. Changing direction always takes time 1. At the start point s the candidate can pick either right or down, and that first choice costs no time.
- Rule 3: The car is filled with fuel before the test. The candidate must reach t as early as possible while using at most fuel.
Following rule 2 means driving to suit the state of the road, so the fuel spent over the same time differs from segment to segment. The integer written on a unit segment is the fuel it takes to drive that segment for time . Changing direction takes no fuel.

The picture above draws two routes that work on the 4 row 6 column example when and . The left route spends 17 fuel and arrives at time 83. It drives 8 unit segments straight and changes direction 3 times. The right route spends only 16 fuel, but it changes direction more often, so its time is 85. A few other routes also arrive at time 83 with at most 19 fuel. No route arrives at t earlier than time 83 while using at most 19 fuel.
Given the state of the grid together with and , find the earliest time to reach t.
Input
The first line has the number of test cases .
The first line of each test case has four integers , , and . is the number of rows of the grid, is the number of columns, is the time to drive one unit segment straight, and is the amount of fuel. (, , )
Then come lines with integers each. The -th integer on the -th line is the fuel of the horizontal segment that joins column and column in row . After that come lines with integers each. The -th integer on the -th line is the fuel of the vertical segment that joins row and row in column .
Every unit segment takes between 1 and 1000 fuel.
Output
For each test case print the answer on its own line. If s to t is possible with at most fuel, print the earliest arrival time. Otherwise print -1.