import sys input = sys.stdin.readline from heapq import heappush,heappop # def divmod(x,mod): # a = x//mod # return a,x-a*mod h,w = map(int,input().split()) gx,gy = [int(x)-1 for x in input().split()] A = [list(map(int,input().split())) for i in range(h)] inf = 10**20 dp = [[[inf]*(500) for i in range(w)] for j in range(h)] dist = [[inf]*w for i in range(h)] step = [[inf]*w for i in range(h)] dist[gx][gy] = A[gx][gy] dp[gx][gy][0] = A[gx][gy] step[gx][gy] = 0 H = [] dx = [1,0,-1,0] dy = [0,1,0,-1] mod2 = 1<<16 heappush(H,(A[gx][gy]<<16)+gx*w+gy) for d in range(500): nH = [] while H: num = heappop(H) c,num = divmod(num,mod2) x,y = divmod(num,w) if dp[x][y][d] != c: continue # print(d,c,x,y) for i in range(4): nx = x+dx[i] ny = y+dy[i] if nx < 0 or nx >= h or ny < 0 or ny >= w: continue nc = c + A[nx][ny] if dist[nx][ny] <= nc: continue if d < 499 and dp[nx][ny][d+1] > nc: dp[nx][ny][d+1] = nc dist[nx][ny] = nc step[nx][ny] = d+1 nnum = (nc<<16)+nx*w+ny heappush(nH,nnum) if nH: H = nH else: break q = int(input()) for _ in range(q): x,y,k = map(int,input().split()) x -= 1 y -= 1 ans = inf k = k**2 nc = k ndp = dp[x][y] for i in range(step[x][y]+1): if ans > ndp[i]+nc: ans = ndp[i]+nc nc += k print(ans)