Under construction

Still being built. Things may change

X Aura

Time limit1sMemory limit2048 MB

Summary
Given a grid of digit heights and an odd exponent X, answer queries for the minimum total penalty of moving between two cells, where each step costs (h1-h2)^X, or report INVALID if the cost can go unbounded below.
Level

Hard9 of 10

Topics
Graph, Shortest path, Dynamic programming
Solved
No attempts yet

Problem

Mount ICPC can be represented as a grid of RR rows (numbered from 11 to RR) and CC columns (numbered from 11 to CC). The cell at row rr and column cc is denoted (r,c)(r, c) and has height Hr,cH_{r,c}. Two cells are adjacent if they share a side. So (r,c)(r, c) is adjacent to (r−1,c)(r - 1, c), (r+1,c)(r + 1, c), (r,c−1)(r, c - 1), and (r,c+1)(r, c + 1), whenever those cells exist.

You can move only between adjacent cells, and each move has a penalty. With an aura XX, which is an odd positive integer, moving from a cell with height h1h_1 to a cell with height h2h_2 gives a penalty of (h1−h2)X(h_1-h_2)^X. The penalty can be negative.

There are QQ independent scenarios. In each one, you start at cell (Rs,Cs)(R_s, C_s) and want to reach cell (Rf,Cf)(R_f, C_f) with the minimum total penalty. In some scenarios the total penalty can become arbitrarily small. Such a scenario is called invalid. For each scenario, find the minimum total penalty, or determine that it is invalid.

Input

The first line contains three integers RR, CC, and XX (1≤R,C≤10001 \le R, C \le 1000; 1≤X≤91 \le X \le 9; XX is odd).

Each of the next RR lines contains a string HrH_r of length CC. Each character is a digit from 0 to 9. The cc-th character of HrH_r is the height Hr,cH_{r,c} of cell (r,c)(r, c).

The next line contains an integer QQ (1≤Q≤100 0001 \le Q \le 100\,000).

Each of the next QQ lines contains four integers RsR_s CsC_s RfR_f CfC_f (1≤Rs,Rf≤R1 \le R_s, R_f \le R; 1≤Cs,Cf≤C1 \le C_s, C_f \le C).

Output

For each scenario, print one line. If the scenario is invalid, print INVALID. Otherwise, print the minimum total penalty from the starting cell to the destination cell as an integer.

Examples3

  1. Example 1

    Input
    3 4 1
    3359
    4294
    3681
    5
    1 1 3 4
    3 3 2 1
    2 2 1 4
    1 3 3 2
    1 1 1 1
    
    Expected output
    2
    4
    -7
    -1
    0
    
  2. Example 2

    Input
    2 4 5
    1908
    2023
    2
    1 1 2 4
    1 1 1 1
    
    Expected output
    INVALID
    INVALID
    
  3. Example 3

    Input
    3 3 9
    135
    357
    579
    2
    3 3 1 1
    2 2 2 2
    
    Expected output
    2048
    0