#include #include using namespace std; using namespace atcoder; //using mint = modint1000000007; //const int mod = 1000000007; //using mint = modint998244353; //const int mod = 998244353; //const int INF = 1e9; //const long long LINF = 1e18; #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep2(i,l,r)for(int i=(l);i<(r);++i) #define rrep(i, n) for (int i = (n) - 1; i >= 0; --i) #define rrep2(i,l,r)for(int i=(r) - 1;i>=(l);--i) #define all(x) (x).begin(),(x).end() #define allR(x) (x).rbegin(),(x).rend() #define P pair template inline bool chmax(A & a, const B & b) { if (a < b) { a = b; return true; } return false; } template inline bool chmin(A & a, const B & b) { if (a > b) { a = b; return true; } return false; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int h, w; cin >> h >> w; vector a(h, vector(w)); rep(i, h)rep(j, w)cin >> a[i][j]; vector>>edge; vector edges(h * w + 1, vector

()); rep(i, h)rep(j, w) { if (h - 1 != i) { int ni = i + 1; int nj = j + 0; int index0 = i * w + j; int index1 = ni * w + nj; int weight = max(a[i][j], a[ni][nj]); edges[weight].push_back({ index0,index1 }); } if (w - 1 != j) { int ni = i + 0; int nj = j + 1; int index0 = i * w + j; int index1 = ni * w + nj; int weight = max(a[i][j], a[ni][nj]); edges[weight].push_back({ index0,index1 }); } } int q; cin >> q; vectorrs(q), cs(q), rt(q), ct(q); rep(i, q)cin >> rs[i] >> cs[i] >> rt[i] >> ct[i]; vector

query(q); rep(i, q) { rs[i]--, cs[i]--, rt[i]--, ct[i]--; query[i].first = rs[i] * w + cs[i]; query[i].second = rt[i] * w + ct[i]; } const int k = h * w + 1; std::vectorok(q, k), ng(q, -1); while (true) { bool fin = true; std::vector>mid(k); for (int i = 0; i < q; ++i) { if (abs(ok[i] - ng[i]) > 1) { fin = false; int m = (ok[i] + ng[i]) / 2; mid[m].push_back(i); } } if (fin)break; dsu uf(h * w); for (int i = 0; i < k; ++i) { for (auto e : edges[i]) { uf.merge(e.first, e.second); } for (int j = 0; j < mid[i].size(); ++j) { int idx = mid[i][j]; if (uf.same(query[idx].first,query[idx].second))ok[mid[i][j]] = i; else ng[mid[i][j]] = i; } } } rep(i, q)cout << ok[i] << endl; return 0; }