#include #define rep(i, n) for (int i = 0; i < (n); i++) #define repr(i, n) for (int i = (n) - 1; i >= 0; i--) using namespace std; using ll = long long; int dp[50][250][250]; ll ep[250][250]; constexpr ll inf = 1e13; void chmin(ll &x, ll y) { x = min(x, y); } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int H, W, GY, GX; cin >> H >> W >> GY >> GX; GY--; GX--; vector> A(H, vector(W)); rep(i, H) rep(j, W) cin >> A[i][j]; rep(k, 50) rep(i, 250) rep(j, 250) dp[k][i][j] = 1e9; dp[0][GY][GX] = A[GY][GX]; const int dy[] = {0, 1, 0, -1}; const int dx[] = {1, 0, -1, 0}; rep(k, 50) { dp[k][GY][GX] = A[GY][GX] + k*k; priority_queue> q; q.emplace(-dp[k][GY][GX], GY, GX); while (!q.empty()) { ll d; int y, x; tie(d, y, x) = q.top(); q.pop(); if (-d > dp[k][y][x]) continue; rep(l, 4) { int ny = y + dy[l]; int nx = x + dx[l]; if (0 <= ny && ny < H && 0 <= nx && nx < W) { if (dp[k][ny][nx] > dp[k][y][x] + A[ny][nx] + k*k) { dp[k][ny][nx] = dp[k][y][x] + A[ny][nx] + k*k; q.emplace(-dp[k][ny][nx], ny, nx); } } } } } ep[GY][GX] = A[GY][GX] + inf; rep(i, 250) rep(j, 250) ep[i][j] = 1e18; priority_queue> q; q.emplace(-ep[GY][GX], GY, GX); while (!q.empty()) { ll d; int y, x; tie(d, y, x) = q.top(); q.pop(); if (-d > ep[y][x]) continue; rep(l, 4) { int ny = y + dy[l]; int nx = x + dx[l]; if (0 <= ny && ny < H && 0 <= nx && nx < W) { if (ep[ny][nx] > ep[y][x] + A[ny][nx] + inf) { ep[ny][nx] = ep[y][x] + A[ny][nx] + inf; q.emplace(-ep[ny][nx], ny, nx); } } } } int Q; cin >> Q; while (Q--) { int y, x; ll k; cin >> y >> x >> k; y--; x--; if (k < 50) { cout << dp[k][y][x] << '\n'; } else { ll d = (abs(GY - y) + abs(GX - x) + 1); cout << ep[y][x] - d * inf + d * k * k << '\n'; } } }