#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; //#define int long long typedef long long ll; typedef unsigned long long ul; typedef unsigned int ui; const ll mod = 1000000009; const ll INF = mod * mod; typedef pair P; #define stop char nyaa;cin>>nyaa; #define rep(i,n) for(int i=0;i=0;i--) #define Rep(i,sta,n) for(int i=sta;i=1;i--) #define Rep1(i,sta,n) for(int i=sta;i<=n;i++) typedef pair LP; typedef vector vec; typedef vector svec; typedef long double ld; typedef pair LDP; const ld eps = 1e-8; struct CHT { vector v; vector memo; int l; bool check(LP a, LP b, LP c) { return (b.first - a.first)*(c.second - b.second) >= (b.second - a.second)*(c.first - b.first); } void build(vector a) { l = 0; per(i, (int)a.size()) { while (v.size() >= 2 && check(v[v.size() - 2], v[v.size() - 1], a[i]))v.pop_back(); v.push_back(a[i]); } } void build() { per(i, (int)memo.size()) { while (v.size() >= 2 && check(v[v.size() - 2], v[v.size() - 1], memo[i]))v.pop_back(); v.push_back(memo[i]); } memo.clear(); } void add(LP a) { memo.push_back(a); } ll f(LP a, ll x) { return a.first*x + a.second; } ll query(ll x) { while (l + 1 < v.size() && f(v[l], x) > f(v[l + 1], x))l++; return f(v[l], x); } }; const int sz = 605; int dx[4] = { 1,0,-1,0 }; int dy[4] = { 0,1,0,-1 }; int a[250][250]; int dist[250][250][sz+1]; CHT cht[250][250]; struct query { int x, y, k, id; }; void solve() { int h, w; cin >> h >> w; int sx, sy = 0; cin >> sx >> sy; sx--; sy--; rep(i, h) { rep(j, w) { cin >> a[i][j]; rep(k, sz + 1) { dist[i][j][k] = mod; } } } dist[sx][sy][1] = a[sx][sy]; //cht[sx][sy].add({ 1,a[sx][sy] }); Rep(k,2, sz + 1) { rep(i, h) { rep(j, w) { if (dist[i][j][k-1] == mod)continue; cht[i][j].add({ k-1,dist[i][j][k - 1] }); rep(t, 4) { int x = i + dx[t]; int y = j + dy[t]; if (x < 0 || y < 0 || x >= h || y >= w)continue; dist[x][y][k] = min(dist[x][y][k], dist[i][j][k - 1] + a[x][y]); } } } } rep(i, h) { rep(j, w) { cht[i][j].build(); } } int q; cin >> q; vector> qmemo; rep(i, q) { int x, y, k; cin >> x >> y >> k; x--; y--; qmemo.push_back({ {k,i},{x,y} }); } sort(qmemo.begin(), qmemo.end()); vector ans(q); rep(i, q) { ll k = qmemo[i].first.first; int id = qmemo[i].first.second; int x = qmemo[i].second.first; int y = qmemo[i].second.second; ans[id] = cht[x][y].query(k*k); } rep(i, q) { cout << ans[i] << endl; } } signed main() { ios::sync_with_stdio(false); cin.tie(0); //cout << fixed << setprecision(10); //init(); solve(); //cout << "finish" << endl; //stop return 0; }