// includes {{{ #include #include #include #include #include #include #include #include #include #include #include #include #include #include // #include // #include // #include // #include // }}} using namespace std; using ll = long long; // 右下にゴールがあるとする // 右下に向かわなかった場合,2 * k^2 の損をする // 得の最大値は 98 * 248 = 24304 = M // M < 2 * k^2 <=> k >= 111 = K // 最短路 // N^2 * log(N^2) * K int h, w; int gx, gy; ll A[250][250]; int q; constexpr int K = 111; constexpr ll inf = 1e18; ll dist[K+1][250][250]; ll steps[K+1][250][250]; int dx[] = {1, 0, -1, 0}; int dy[] = {0, 1, 0, -1}; int main() { std::ios::sync_with_stdio(false), std::cin.tie(0); cin >> h >> w; cin >> gx >> gy; gx--, gy--; for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) cin >> A[i][j]; for(int k = 1; k <= K; k++) { for(int i = 0; i < h; i++) for(int j = 0; j < w; j++) dist[k][i][j] = inf; using P = tuple; priority_queue, greater

> pq; dist[k][gx][gy] = k * k + A[gx][gy]; steps[k][gx][gy] = 1; pq.emplace(dist[k][gx][gy], gx, gy, 1); while(pq.size()) { ll d; int x, y, s; tie(d, x, y, s) = pq.top(); pq.pop(); if(dist[k][x][y] < d) continue; for(int dir = 0; dir < 4; dir++) { int nx = x + dx[dir]; int ny = y + dy[dir]; if(0 <= nx and nx < h and 0 <= ny and ny < w); else continue; ll nd = d + k * k + A[nx][ny]; if(nd < dist[k][nx][ny]) { dist[k][nx][ny] = nd; steps[k][nx][ny] = s + 1; pq.emplace(nd, nx, ny, s + 1); } } } } cin >> q; for(int i = 0; i < q; i++) { ll x, y, k; cin >> x >> y >> k; x--, y--; ll r = min(K, k); ll ans = dist[r][x][y] + (k * k - r * r) * steps[r][x][y]; cout << ans << "\n"; } return 0; }