#include int ri() { int n; scanf("%d", &n); return n; } std::pair dirs[] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; int main() { int h = ri(), w = ri(); int gx = ri() - 1, gy = ri() - 1; int a[h][w]; for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) a[i][j] = ri(); using T = std::pair >; std::vector > dist[350]; for (int i = 1; i < 350; i++) { int64_t cost_base = i * i; dist[i].resize(h, std::vector(w, 1000000000000000000)); std::priority_queue, std::greater > que; que.push({a[gx][gy] + cost_base, {gx, gy}}); dist[i][gx][gy] = a[gx][gy] + cost_base; while (que.size()) { auto cur = que.top(); que.pop(); for (auto d : dirs) { int x = cur.second.first + d.first; int y = cur.second.second + d.second; if (x < 0 || x >= h || y < 0 || y >= w) continue; int64_t new_cost = cur.first + cost_base + a[x][y]; if (dist[i][x][y] > new_cost) { dist[i][x][y] = new_cost; que.push({new_cost, {x, y}}); } } } } std::vector > normal_dist(h, std::vector(w, 1000000000000000000)); normal_dist[gx][gy] = a[gx][gy]; std::queue > que; que.push({gx, gy}); while (que.size()) { auto cur = que.front(); que.pop(); for (auto d : dirs) { int x = cur.first + d.first; int y = cur.second + d.second; if (x < 0 || x >= h || y < 0 || y >= w) continue; if (std::abs(cur.first - gx) + std::abs(cur.second - gy) >= std::abs(x - gx) + std::abs(y - gy)) continue; int64_t new_cost = normal_dist[cur.first][cur.second] + a[x][y]; if (normal_dist[x][y] > new_cost) { normal_dist[x][y] = new_cost; que.push({x, y}); } } } int q = ri(); for (int i = 0; i < q; i++) { int x = ri() - 1; int y = ri() - 1; int k = ri(); if (k < 350) { std::cout << dist[k][x][y] << std::endl; } else std::cout << normal_dist[x][y] + (int64_t) k * k * (std::abs(x - gx) + std::abs(y - gy) + 1) << std::endl; } return 0; }