Under construction

Still being built. Things may change

Shortest Path Queries

Time limit5sMemory limit512 MB

Summary
Given a W by H grid of cell costs, the task answers Q queries with the minimum-cost path sum between two cells, moving only to edge-adjacent cells.
Level

Medium7 of 10

Topics
Divide and conquer, Dynamic programming, Matrix
Solved
No attempts yet

Problem

You are given a W×HW \times H grid. Each cell contains an integer. The top-left cell is called (1,1)(1, 1), and the bottom-right cell is called (W,H)(W, H).

A path from a cell SS to a cell TT is a sequence of cells such that the first cell in the sequence is SS, the last cell is TT, and any two consecutive cells share an edge. The cost of a path is the sum of the costs of all cells in the path.

You are given the integers written in the grid and QQ pairs of cells (SXi,SYi)(SX_i, SY_i) and (TXi,TYi)(TX_i, TY_i). For each pair, compute the minimum cost of a path from cell (SXi,SYi)(SX_i, SY_i) to cell (TXi,TYi)(TX_i, TY_i).

Input

The first line contains three integers WW, HH, and QQ (1≤W≤101 \le W \le 10, 2≤H≤1042 \le H \le 10^4, 1≤Q≤1051 \le Q \le 10^5).

The next HH lines describe the grid. The xx-th number on the yy-th of these lines, Ax,yA_{x,y}, is the integer written in cell (x,y)(x, y) (0≤Ax,y≤1090 \le A_{x,y} \le 10^9).

The next QQ lines each contain a pair of cells (SXi,SYi)(SX_i, SY_i) and (TXi,TYi)(TX_i, TY_i) (1≤SXi,TXi≤W1 \le SX_i, TX_i \le W, 1≤SYi,TYi≤H1 \le SY_i, TY_i \le H, (SXi,SYi)≠(TXi,TYi)(SX_i, SY_i) \ne (TX_i, TY_i)).

Output

Print QQ lines. On the ii-th line, print the minimum cost for the pair (SXi,SYi)(SX_i, SY_i) and (TXi,TYi)(TX_i, TY_i).

Examples2

  1. Example 1

    Input
    2 5 4
    0 1
    0 1
    0 0
    1 0
    1 0
    1 1 2 5
    2 1 1 5
    1 3 2 3
    1 5 1 1
    
    Expected output
    0
    2
    0
    1
    
  2. Example 2

    Input
    3 6 5
    1 9 2
    3 4 1
    2 5 3
    4 2 2
    3 1 5
    2 6 3
    1 1 3 1
    1 1 3 6
    1 6 3 6
    1 3 3 4
    2 6 3 2
    
    Expected output
    11
    21
    11
    10
    15