#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; void Main() { int H,W,gi,gj; cin >> H >> W >> gi >> gj; gi--; gj--; vector> A(H,vector(W)); for(int i = 0;i < H;i++) { for(int j = 0;j < W;j++) { cin >> A[i][j]; } } vector> cost(H,vector(W,(int)1e9)); const int d[5] = {0,1,0,-1}; cost[gi][gj] = A[gi][gj]; auto dfs = [&](auto dfs,int i,int j) -> int { if(cost[i][j] < (int)1e9) { return cost[i][j]; } int res = (int)1e9; if(i < gi) { res = min(res,dfs(dfs,i + 1,j) + A[i][j]); } if(i > gi) { res = min(res,dfs(dfs,i - 1,j) + A[i][j]); } if(j < gj) { res = min(res,dfs(dfs,i,j + 1) + A[i][j]); } if(j > gj) { res = min(res,dfs(dfs,i,j - 1) + A[i][j]); } return cost[i][j] = res; }; for(int i = 0;i < H;i++) { for(int j = 0;j < W;j++) { dfs(dfs,i,j); } } /* { */ /* queue> Q; */ /* Q.push(make_pair(gi,gj)); */ /* while(!Q.empty()) */ /* { */ /* auto [i,j] = Q.front(); */ /* Q.pop(); */ /* for(int k = 0;k < 4;k++) */ /* { */ /* int ni = i + d[k]; */ /* int nj = j + d[k + 1]; */ /* if(ni < 0 || nj < 0 || ni >= H || nj >= W) */ /* { */ /* continue; */ /* } */ /* if(cost[ni][nj] == (int)1e9) */ /* { */ /* Q.push(make_pair(ni,nj)); */ /* } */ /* cost[ni][nj] = min(cost[ni][nj],cost[i][j] + A[ni][nj]); */ /* } */ /* } */ /* } */ vector>> dp(H,vector>(W,vector(10,(int)1e9))); for(int k = 1;k <= 9;k++) { dp[gi][gj][k] = k * k + A[gi][gj]; priority_queue>> Q; Q.push(make_pair(-dp[gi][gj][k],make_pair(gi,gj))); while(!Q.empty()) { int cur = - Q.top().first; auto [i,j] = Q.top().second; Q.pop(); if(dp[i][j][k] < cur) { continue; } for(int r = 0;r < 4;r++) { int ni = i + d[r]; int nj = j + d[r + 1]; if(ni < 0 || nj < 0 || ni >= H || nj >= W) { continue; } if(dp[ni][nj][k] > dp[i][j][k] + k * k + A[ni][nj]) { dp[ni][nj][k] = dp[i][j][k] + k * k + A[ni][nj]; Q.push(make_pair(-dp[ni][nj][k],make_pair(ni,nj))); } } } } int Q; cin >> Q; for(;Q--;) { int x,y,k; cin >> x >> y >> k; x--; y--; long long ans = 0; if(k >= 10) { ans = (long long) k * k * (abs(x - gi) + abs(y - gj) + 1) + cost[x][y]; } else { ans = dp[x][y][k]; } cout << ans << "\n"; } } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tt = 1; /* cin >> tt; */ while(tt--) Main(); }