#include #include #include #include #include #include // タプルを使うために必要 using namespace std; int main() { int H, W; cin >> H >> W; int gx, gy; cin >> gx >> gy; gx--; gy--; vector> A(H, vector(W)); for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { cin >> A[h][w]; } } int Q; cin >> Q; const int K = 251; vector>> query(K + 1); for (int q = 0; q < Q; ++q) { int x, y, k; cin >> x >> y >> k; x--; y--; // std::make_tupleを使ってタプルを作成 query[min(k, K)].push_back(make_tuple(x, y, k, q)); } vector ans_lst(Q); for (int k = 0; k <= K; ++k) { long long w = k < K ? k * k : (1 << 30); long long inf = (1LL << 60); vector> dist(H, vector(W, inf)); dist[gx][gy] = 0; priority_queue> queue; queue.push(make_tuple(-dist[gx][gy], gx, gy)); while (!queue.empty()) { auto [d, x, y] = queue.top(); queue.pop(); d = -d; for (auto [dx, dy] : vector>{{0,1},{1,0},{0,-1},{-1,0}}) { int xx = x + dx, yy = y + dy; if (0 <= xx && xx < H && 0 <= yy && yy < W) { long long dd = d + w + A[xx][yy]; if (dist[xx][yy] > dd) { dist[xx][yy] = dd; queue.push(make_tuple(-dd, xx, yy)); } } } } for (auto [x, y, c, q] : query[k]) { if (k < K) { ans_lst[q] = dist[x][y] + c * c + A[gx][gy]; } else { long long cnt = dist[x][y] / w; long long d = dist[x][y] % w; ans_lst[q] = (cnt + 1) * c * c + d + A[gx][gy]; } } } for (int i = 0; i < Q; ++i) { cout << ans_lst[i] << endl; } return 0; }