#include #include #include #include using namespace std; typedef long long ll; int h, w; vector> ban; vector>>> dp; void bfs(vector start) { priority_queue, vector>, greater<>> que; que.push(start); vector mx{1, -1, 0, 0}; vector my{0, 0, 1, -1}; while (true) { if (que.empty())break; vector now = que.top(); que.pop(); auto &v = dp[now[2]][now[3]]; if (now[1] >= v[v.size() - 1].second)continue; v.push_back({now[0], now[1]}); for (int i = 0; i < 4; i++) { int ax = now[2] + mx[i]; int ay = now[3] + my[i]; if (0 <= ax && ax < h && 0 <= ay && ay < w) { auto nv = dp[ax][ay]; if (now[1] + ban[ax][ay] < nv[nv.size() - 1].second) que.push({now[0] + 1, now[1] + ban[ax][ay], ax, ay}); } } } } int main() { int gx, gy; cin >> h >> w >> gx >> gy; gx--; gy--; ban = vector>(h, vector(w)); for (int i = 0; i < h; i++) for (int j = 0; j < w; j++)cin >> ban[i][j]; dp = vector>>> (h, vector>>(w, vector>{{0, 1145141919810364}})); bfs({1, ban[gx][gy], gx, gy}); int q; cin >> q; for (int i = 0; i < q; i++) { ll x, y, k; cin >> x >> y >> k; x--; y--; ll ret = 1145141919810364364; for (auto usi:dp[x][y]) { ret = min(ret, k * k * usi.first + usi.second); } cout << ret << endl; } return 0; }