#include #include #include #include #include #include #include #include #include #include #include using namespace std; /*int p = 998244353;*/ int p = 1000000007; #define vel vector #define vvel vector #define rep(i,n) for(int i=0;i #define qin pair #define V vector #define Endl endl #define veb vector #define sq(a) (a)*(a) #define rev(s) reverse(s.begin(),s.end()) #define end_pr(s) cout << s < q; q.push(mid1); while (!q.empty()) { int st = q.front(); q.pop(); rep(i, way[st].size()) { int to = way[st][i]; if (dist[to] == -1) { dist[to] = dist[st] + 1; q.push(to); } } } return dist; } pin most_far(int now, int n, vvel &way) { vel dist1 = dis(now, way); pin ans = mkp(-1, 0); rep(i, n) { if (dist1[i] > ans.first) { ans = mkp(dist1[i], i); } } return ans; } template V uni(V &v) { if (v.size() == 0) { return v; } sor(v); V ans(1, v[0]); for (int i = 1; i < v.size(); i++) { if (v[i] != v[i - 1]) { ans.push_back(v[i]); } } v = ans; return v; } int s_gcd(int a, int b) { if (b == 0) { return a; } return s_gcd(b, a%b); } int gcd(int a, int b) { a = abs(a); b = abs(b); if (a < b) { swap(a, b); } return s_gcd(a, b); } int solve(int sum, int lim) { if (sum <= lim) { return sum - 1; } if (sum > lim * 2) { return 0; } return lim * 2 - sum+1; } vel dx{ 1,-1,0,0 }; vel dy{ 0,0,1,-1 }; vvel dijk(vvel &a, int h, int w, int k,int gx,int gy) { priority_queue,greater> pq; vvel dist(h, vel(w, -1)); pq.push(mkp(0, mkp(gx, gy))); while (!pq.empty()) { qin sm = pq.top(); pq.pop(); pin pot = sm.second; int x = pot.first; int y = pot.second; int dis1 = sm.first; if (dist[x][y] == -1) { dist[x][y] = dis1; rep(i, 4) { int mx = x + dx[i]; int my = y + dy[i]; if (0 <= mx and mx < h and 0 <= my and my < w) { if (dist[mx][my] == -1) { pq.push(mkp(dis1 + k * k + a[mx][my], mkp(mx, my))); } } } } } rep(i, h) { rep(j, w) { dist[i][j] += (k * k + a[gx][gy]); } } return dist; } int upper = 160; signed main() { int h, w; cin >> h >> w; int gx, gy; cin >> gx >> gy; gx--; gy--; vvel a(h, vel(w)); rep(i, h) { rep(j, w) { cin >> a[i][j]; } } V dist(upper+1, vvel(h, vel(w))); for (int k = 1; k <= upper; k++) { dist[k] = dijk(a, h, w, k,gx,gy); } int q; cin >> q; rep(i, q) { int x, y;long long k; cin >> x >> y >> k; x--; y--; if (k <= upper) { cout << dist[k][x][y] << endl; } else { int qans = dist[k][x][y]; int c_dis = abs(x - gx) + abs(y - gy); c_dis++; long long mul = (k*k) - upper * upper; qans += c_dis + mul; } } }