#include #include #include #include #include using namespace std; #pragma warning (disable: 4996) long long H, W, Q, gx, gy, A[259][259]; long long val[259][259][259], dist[259][259]; priority_queue, vector>, greater>> Que; void dijkstra(long long r) { for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) dist[i][j] = (1LL << 62); } dist[gx][gy] = 1LL * (r*r + A[gx][gy]); Que.push(make_tuple(dist[gx][gy], gx, gy)); int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0,1, 0, -1 }; while (!Que.empty()) { tuple tup = Que.top(); Que.pop(); int cx = get<1>(tup), cy = get<2>(tup); for (int i = 0; i < 4; i++) { int ex = cx + dx[i], ey = cy + dy[i]; if (ex <= 0 || ey <= 0 || ex > H || ey > W) continue; long long cost = r * r + A[ex][ey]; if (dist[ex][ey] > dist[cx][cy] + 1LL * cost) { dist[ex][ey] = dist[cx][cy] + 1LL * cost; Que.push(make_tuple(dist[ex][ey], ex, ey)); } } } } int main() { scanf("%lld%lld%lld%lld", &H, &W, &gx, &gy); for (int i = 1; i <= H; i++) { for (int j = 1; j <= W; j++) scanf("%lld", &A[i][j]); } for (int i = 1; i <= 250; i++) { dijkstra(i); for (int j = 1; j <= H; j++) { for (int k = 1; k <= W; k++) val[i][j][k] = dist[j][k]; } } scanf("%lld", &Q); for (int i = 1; i <= Q; i++) { long long cx, cy, k; scanf("%lld%lld%lld", &cx, &cy, &k); k = min(k, 250LL); printf("%lld\n", val[k][cx][cy]); } return 0; }