#include #define rep(i,a,b) for(int i=a;i=b;i--) #define fore(i,a) for(auto &i:a) #define all(x) (x).begin(),(x).end() //#pragma GCC optimize ("-O3") using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); } typedef long long ll; const int inf = INT_MAX / 2; const ll infl = 1LL << 60; templatebool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; } templatebool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; } //--------------------------------------------------------------------------------------------------- template using min_priority_queue = priority_queue, greater>; int dx[4] = { 0, 1, 0, -1 }, dy[4] = { -1, 0, 1, 0 }; /*---------------------------------------------------------------------------------------------------             ∧_∧       ∧_∧  (´<_` )  Welcome to My Coding Space!      ( ´_ゝ`) /  ⌒i @hamayanhamayan     /   \    | |     /   / ̄ ̄ ̄ ̄/  |   __(__ニつ/  _/ .| .|____      \/____/ (u ⊃ ---------------------------------------------------------------------------------------------------*/ int H, W, gx, gy, A[251][251], Q, X[501010], Y[501010], K[501010]; ll ans[1010101]; vector query[1010101]; //--------------------------------------------------------------------------------------------------- ll dst[251][251]; bool vis[251][251]; int idx[251][251]; void _main() { cin >> H >> W >> gy >> gx; gx--; gy--; rep(y, 0, H) rep(x, 0, W) cin >> A[y][x]; cin >> Q; rep(i, 0, Q) cin >> Y[i] >> X[i] >> K[i], X[i]--, Y[i]--; rep(q, 0, Q) query[K[q]].push_back(q); // small pattern rep(k, 1, 300) { if (query[k].size() == 0) continue; rep(y, 0, H) rep(x, 0, W) dst[y][x] = infl, vis[y][x] = false; min_priority_queue> que; dst[gy][gx] = k * k + A[gy][gx]; que.push({ dst[gy][gx], gy * W + gx }); while (!que.empty()) { auto q = que.top(); que.pop(); ll cst = q.first; int y = q.second / W; int x = q.second % W; if (vis[y][x]) continue; vis[y][x] = true; rep(d, 0, 4) { int xx = x + dx[d]; int yy = y + dy[d]; if (0 <= xx and xx < W and 0 <= yy and yy < H) { if (chmin(dst[yy][xx], cst + A[yy][xx] + k * k)) { que.push({ dst[yy][xx] , yy * W + xx}); } } } } fore(q, query[k]) ans[q] = dst[Y[q]][X[q]]; } queue> que; rep(y, 0, H) rep(x, 0, W) dst[y][x] = infl, vis[y][x] = false; que.push({ gx, gy }); dst[gy][gx] = A[gy][gx]; vis[gy][gx] = true; idx[gy][gx] = 0; while (!que.empty()) { int x, y; tie(x, y) = que.front(); que.pop(); rep(d, 0, 4) { int xx = x + dx[d]; int yy = y + dy[d]; if (0 <= xx and xx < W and 0 <= yy and yy < H) { if (!vis[yy][xx]) { que.push({ xx, yy }); vis[yy][xx] = true; idx[yy][xx] = idx[gy][gx] + 1; } if(idx[y][x] + 1 == idx[yy][xx]) chmin(dst[yy][xx], dst[y][x] + A[yy][xx]); } } } // big pattern rep(k, 300, 1010101) fore(q, query[k]) { int x = X[q], y = Y[q]; ans[q] = dst[y][x] + 1LL * (abs(y - gy) + abs(x - gx) + 1) * k * k; } rep(i, 0, Q) printf("%lld\n", ans[i]); }