#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[500][250][250]; constexpr int inf = 1e9; 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, 500) rep(i, 250) rep(j, 250) dp[k][i][j] = inf; dp[0][GY][GX] = A[GY][GX]; const int dy[] = {0, 1, 0, -1}; const int dx[] = {1, 0, -1, 0}; rep(k, 500-1) { rep(i, H) rep(j, W) { rep(l, 4) { int ni = i + dy[l]; int nj = j + dx[l]; if (0 <= ni && ni < H && 0 <= nj && nj < W) { dp[k+1][ni][nj] = min(dp[k+1][ni][nj], dp[k][i][j] + A[ni][nj]); } } } } int Q; cin >> Q; while (Q--) { int y, x; ll k; cin >> y >> x >> k; y--; x--; ll ans = 1e18; rep(i, 500) { ans = min(ans, dp[i][y][x] + (i+1) * k * k); } cout << ans << '\n'; } }