Treasure Lair

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

요약
각 질의 칸에서 보물 K개를 시작 칸으로 가져오는 최소 시간을 구한다. 이동은 8방향이고 한 번에 보물 하나만 옮길 수 있다.
난이도

보통10점 중 7점

유형
BFS, 정렬, 누적 합, 그리디
정답자
아직 제출이 없습니다

문제

During your recent exploration, you come across a treasure lair that can be represented as a grid with NN rows (numbered from 11 to NN) and MM columns (numbered from 11 to MM). The cell at row rr and column cc is denoted as (r,c)(r, c). Cell (r,c)(r, c) contains a treasure if A_r,c=1A\_{r,c} = 1, and it is empty if A_r,c=0A\_{r,c} = 0.

There are QQ independent scenarios. For each scenario, you start in cell (R,C)(R, C) and you want to take exactly KK treasures. In one second, you can move to any orthogonally or diagonally adjacent cell to the cell you are currently in, as shown in the following illustration. Since the treasures are heavy, you can only carry one treasure at a time, meaning you must bring the treasure back to cell (R,C)(R, C) before going for the next one or completing the scenario. The action of taking or putting down a treasure takes zero seconds.

For each scenario, determine the minimum required time (in seconds) to take KK treasures back to cell (R,C)(R, C) if you start in (R,C)(R, C). As all scenarios are independent of each other, the treasures are back to their original positions at the beginning of a scenario.

입력

The first line consists of two integers NN MM (1≤N,M≤10001 ≤ N, M ≤ 1000).

Each of the next NN lines consists of a binary string A_iA\_i of length MM. The jjth character of string A_iA\_i describes cell (i,j)(i, j): it is 11 if cell (i,j)(i, j) contains a treasure, and 00 if cell (i,j)(i, j) is empty. The number of treasures in the lair is at least one.

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

Each of the next QQ lines consists of three integers RR CC KK (1≤R≤N1 ≤ R ≤ N; 1≤C≤M1 ≤ C ≤ M; 1≤K1 ≤ K) describing each scenario. The value of KK does not exceed the number of treasures in the lair.

출력

For each scenario, output an integer in a single line representing the minimum required time (in seconds) to take KK treasures back to cell (R,C)(R, C) if you start in (R,C)(R, C).

예제2

  1. 예제 1

    입력
    5 5
    11010
    01001
    10001
    00111
    11010
    6
    1 1 1
    1 1 3
    1 1 13
    2 3 6
    4 1 8
    1 5 3
    
    예상 출력
    0
    4
    74
    18
    32
    8
    
  2. 예제 2

    입력
    1 10
    0000011111
    3
    1 1 1
    1 1 5
    1 10 5
    
    예상 출력
    10
    70
    20