#pragma GCC optimize ("Ofast") #pragma GCC optimize ("unroll-loops") #pragma GCC target ("avx") #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using Int = long long; template ostream &operator<<(ostream &os, const pair &a) { return os << "(" << a.first << ", " << a.second << ")"; }; template void pv(T a, T b) { for (T i = a; i != b; ++i) cerr << *i << " "; cerr << endl; } template void chmin(T &t, const T &f) { if (t > f) t = f; } template void chmax(T &t, const T &f) { if (t < f) t = f; } constexpr Int INF = 1001001001001001001LL; constexpr int MAX = 260; constexpr int L = 224; int H, W; int GX, GY; Int A[MAX][MAX]; int Q; int X[500010], Y[500010]; Int K[500010]; Int dist[L + 10][MAX][MAX]; Int dp[MAX][MAX]; int main() { for (; ~scanf("%d%d", &H, &W); ) { scanf("%d%d", &GX, &GY); --GX; --GY; for (int x = 0; x < H; ++x) for (int y = 0; y < W; ++y) { scanf("%lld", &A[x][y]); } scanf("%d", &Q); for (int q = 0; q < Q; ++q) { scanf("%d%d%lld", &X[q], &Y[q], &K[q]); --X[q]; --Y[q]; } // small for (int k = 0; k < L; ++k) { const Int k2 = 1LL * k * k; using Node = pair>; priority_queue, greater> q; for (int x = 0; x < H; ++x) for (int y = 0; y < W; ++y) { dist[k][x][y] = INF; } dist[k][GX][GY] = k2 + A[GX][GY]; q.emplace(dist[k][GX][GY], make_pair(GX, GY)); for (; !q.empty(); ) { const Int c = q.top().first; const int x = q.top().second.first; const int y = q.top().second.second; q.pop(); if (dist[k][x][y] == c) { auto update = [&](int xx, int yy) { const Int cc = c + k2 + A[xx][yy]; if (dist[k][xx][yy] > cc) { dist[k][xx][yy] = cc; q.emplace(cc, make_pair(xx, yy)); } }; if (x + 1 < H) update(x + 1, y); if (y + 1 < W) update(x, y + 1); if (x - 1 >= 0) update(x - 1, y); if (y - 1 >= 0) update(x, y - 1); } } } // large for (int x = 0; x < H; ++x) for (int y = 0; y < W; ++y) { dp[x][y] = INF; } dp[GX][GY] = A[GX][GY]; for (int x = GX; x < H; ++x) for (int y = GY; y < W; ++y) { if (x > GX) chmin(dp[x][y], dp[x - 1][y] + A[x][y]); if (y > GY) chmin(dp[x][y], dp[x][y - 1] + A[x][y]); } for (int x = GX; x < H; ++x) for (int y = GY; y >= 0; --y) { if (x > GX) chmin(dp[x][y], dp[x - 1][y] + A[x][y]); if (y < GY) chmin(dp[x][y], dp[x][y + 1] + A[x][y]); } for (int x = GX; x >= 0; --x) for (int y = GY; y < W; ++y) { if (x < GX) chmin(dp[x][y], dp[x + 1][y] + A[x][y]); if (y > GY) chmin(dp[x][y], dp[x][y - 1] + A[x][y]); } for (int x = GX; x >= 0; --x) for (int y = GY; y >= 0; --y) { if (x < GX) chmin(dp[x][y], dp[x + 1][y] + A[x][y]); if (y < GY) chmin(dp[x][y], dp[x][y + 1] + A[x][y]); } for (int q = 0; q < Q; ++q) { Int ans; if (K[q] < L) { ans = dist[K[q]][X[q]][Y[q]]; } else { ans = 1LL * K[q] * K[q] * (1 + abs(X[q] - GX) + abs(Y[q] - GY)) + dp[X[q]][Y[q]]; } printf("%lld\n", ans); } } return 0; }