X Aura

시간 제한1초메모리 제한2048 MB

요약
격자 위 두 칸 사이를 이동할 때 발생하는 총 페널티의 최솟값을 구하고, 페널티가 한없이 작아질 수 있으면 INVALID를 출력한다.
난이도

어려움10점 중 8점

유형
최단 경로, 그래프, 그리디
정답자
아직 제출이 없습니다

문제

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 located at row rr and column cc is denoted as (r,c)(r, c) and has a height of H_r,cH\_{r,c}. Two cells are adjacent to each other if they share a side. Formally, (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), if any exists.

You can move only between adjacent cells, and each move comes with a penalty. With an aura of an odd positive integer XX, moving from a cell with height h_1h\_1 to a cell with height h_2h\_2 gives you a penalty of (h_1−h_2)X(h\_1-h\_2)^X. Note that the penalty can be negative.

You want to answer QQ independent scenarios. In each scenario, you start at the starting cell (R_s,C_s)(R\_s, C\_s) and you want to go to the destination cell (R_f,C_f)(R\_f , C\_f ) with minimum total penalty. In some scenarios, the total penalty might become arbitrarily small; such a scenario is called invalid. Find the minimum total penalty to move from the starting cell to the destination cell, or determine if the scenario is invalid.

입력

The first line consists of three integers RR CC XX (1≤R,C≤10001 ≤ R, C ≤ 1000; 1≤X≤91 ≤ X ≤ 9; XX is an odd integer).

Each of the next RR lines consists of a string H_rH\_r of length CC. Each character in H_rH\_r is a number from 00 to 99. The ccth character of H_rH\_r represents the height of cell (r,c)(r, c), or H_r,cH\_{r,c}.

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

Each of the next QQ lines consists of four integers R_sR\_s C_sC\_s R_fR\_f C_fC\_f (1≤R_s,R_f≤R1 ≤ R\_s, R\_f ≤ R; 1≤C_s,C_f≤C1 ≤ C\_s, C\_f ≤ C).

출력

For each scenario, output the following in a single line. If the scenario is invalid, output INVALID. Otherwise, output a single integer representing the minimum total penalty to move from the starting cell to the destination cell.

예제3

  1. 예제 1

    입력
    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
    
    예상 출력
    2
    4
    -7
    -1
    0
    
  2. 예제 2

    입력
    2 4 5
    1908
    2023
    2
    1 1 2 4
    1 1 1 1
    
    예상 출력
    INVALID
    INVALID
    
  3. 예제 3

    입력
    3 3 9
    135
    357
    579
    2
    3 3 1 1
    2 2 2 2
    
    예상 출력
    2048
    0