Under construction

Still being built. Things may change

Good Word, Bad Word

Time limit2.5sMemory limit1024 MB

Summary
Bacteria on an N by N grid can step to an orthogonal neighbor for cost a, or jump up to Chebyshev distance D from a good cell for cost b; for each meeting cell find the total minimum cost for all bacteria to reach it.
Level

Hard9 of 10

Topics
Shortest path, Graph, BFS, Matrix
Solved
No attempts yet

Problem

An onion is planted in each cell of an N×NN \times N grid. Each onion is home to one bacterium, and these bacteria hold meetings often. In this grid, the coordinate (r,c)(r, c) denotes the cell in the rr-th row and cc-th column. Each bacterium has two ways to move: the good word and the bad word. Saying the bad word once consumes aa energy. To say the good word, the cell the bacterium is currently in must be a good cell, and saying it consumes bb energy. If the current position is (r,c)(r, c), saying the bad word makes the angry onion shove the bacterium to a neighboring onion, so the bacterium can move to any (r′,c′)(r', c') satisfying ∣r′−r∣+∣c′−c∣=1|r' - r|+|c' - c| = 1; saying the good word makes the onion grow instantly and toss the bacterium high, so the bacterium can move to any (r′,c′)(r', c') satisfying max⁡(∣r′−r∣,∣c′−c∣)≤D\max(|r' - r|, |c' - c|) \le D. Moving outside the grid is of course impossible.

The meeting scheduled for day ii is held at (Ri,Ci)(R_i, C_i), and the day's sunlight intensity determines a=Aia = A_i and b=Bib = B_i. Assuming each bacterium moves using the minimum energy, find the total energy the bacteria must spend for all bacteria in the grid to gather. The onions can move only one bacterium at a time. After the meeting ends, every bacterium returns to the onion it lives in, and this costs no energy.

Input

The first line gives the grid size NN, the movement range DD of the good word, and the number of meeting days QQ, separated by spaces.

Line i+1i + 1 gives the state of row ii of the grid as a string of length NN. If the jj-th character is ., then (i,j)(i, j) is a bad cell; if it is #, it is a good cell. (1≤i,j≤N1 \le i, j \le N)

Line i+N+1i + N + 1 gives the information for the meeting on day ii: RiR_i, CiC_i, AiA_i, BiB_i, separated by spaces. (1≤i≤Q1 \le i \le Q)

Output

On line ii, print the total energy the bacteria must spend at the meeting on day ii. (1≤i≤Q1 \le i \le Q)

Constraints

  • 1≤D≤N≤5001 \le D \le N \le 500
  • 1≤Q≤51 \le Q \le 5
  • 1≤Ri,Ci≤N1 \le R_i, C_i \le N (1≤i≤Q1 \le i \le Q)
  • 1≤Ai,Bi≤1091 \le A_i, B_i \le 10^9 (1≤i≤Q1 \le i \le Q)

Examples2

  1. Example 1

    Input
    3 1 2
    #..
    ...
    ...
    1 1 10 1
    2 2 1 1
    
    Expected output
    180
    11
    
  2. Example 2

    Input
    8 2 4
    ........
    ........
    ....#...
    ........
    .......#
    ..#..#..
    ........
    ........
    6 1 3 1
    8 2 100 1
    4 3 1 3
    2 4 1 100
    
    Expected output
    605
    17798
    263
    304