from collections import deque H,W = map(int,input().split()) gx,gy = map(int,input().split()) A = list(list(map(int,input().split()))for i in range(H)) cost = [[[[0,float('inf')]]for i in range(W)]for j in range(H)] cost[gx-1][gy-1][-1] = [1,A[gx-1][gy-1]] queue = deque([[gy-1,gx-1]]) while queue != deque([]): qx,qy = queue.popleft() if qx < W-1 and cost[qy][qx+1][-1][1] > cost[qy][qx][-1][1] + A[qy][qx+1]: cost[qy][qx+1].append([cost[qy][qx][-1][0]+1,cost[qy][qx][-1][1] + A[qy][qx+1]]) queue.append([qx+1,qy]) if qx > 0 and cost[qy][qx-1][-1][1] > cost[qy][qx][-1][1] + A[qy][qx-1]: cost[qy][qx-1].append([cost[qy][qx][-1][0]+1,cost[qy][qx][-1][1] + A[qy][qx-1]]) queue.append([qx-1,qy]) if qy > 0 and cost[qy-1][qx][-1][1] > cost[qy][qx][-1][1] + A[qy-1][qx]: cost[qy-1][qx].append([cost[qy][qx][-1][0]+1,cost[qy][qx][-1][1] + A[qy-1][qx]]) queue.append([qx,qy-1]) if qy < H-1 and cost[qy+1][qx][-1][1] > cost[qy][qx][-1][1] + A[qy+1][qx]: cost[qy+1][qx].append([cost[qy][qx][-1][0]+1,cost[qy][qx][-1][1] + A[qy+1][qx]]) queue.append([qx,qy+1]) Q = int(input()) ans = [] for i in range(Q): x,y,k = map(int,input().split()) hoge = float('inf') for a,b in cost[x-1][y-1]: hoge = min(a*k**2+b,hoge) ans.append(hoge) for i in ans: print(i)