/** * Created by 5cm/s on 2024/06/15 10:34:07. * 诸天神佛,佑我上分! **/ #include using namespace std; #define itr(it) begin(it), end(it) #define endl '\n' #define YES() void(cout << "YES\n") #define NO() void(cout << "NO\n") class DSU { vector fa, sz; public: explicit DSU(int n) : fa(n), sz(n, 1) { iota(begin(fa), end(fa), 0); } int find(int i) { return i == fa[i] ? i : (fa[i] = find(fa[i])); } void join(int i, int j) { int a = find(i), b = find(j); if (a == b) return; if (sz[a] < sz[b]) swap(a, b); fa[b] = a, sz[a] += sz[b]; } int operator[](const int i) { return find(i); } int size(int i) { return sz[find(i)]; } void reset() { iota(begin(fa), end(fa), 0); fill(begin(sz), end(sz), 1); } }; // @formatter:off int dxy[][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; // @formatter:on void elysia() { int n, m; cin >> n >> m; int k = n * m; vector a(k), id(k), rk(k); for (int &x: a) cin >> x; iota(itr(id), 0); sort(itr(id), [&](int i, int j) { return a[i] < a[j]; }); for (int i = 0; i < k; ++i) rk[id[i]] = i; int q; cin >> q; vector l(q), r(q); for (int i = 0; i < q; ++i) { int sx, sy, tx, ty; cin >> sx >> sy >> tx >> ty; l[i] = (sx - 1) * m + sy - 1, r[i] = (tx - 1) * m + ty - 1; } vector lo(q), hi(q, k), mid(q); DSU dsu(k); while (true) { bool end = true; vector> at(k); for (int i = 0; i < q; ++i) { if (lo[i] != hi[i]) { end = false; mid[i] = (lo[i] + hi[i]) / 2; at[mid[i]].emplace_back(i); } } if (end) break; dsu.reset(); for (int i = 0, j = 0; i < k; ++i) { while (j < k && a[id[j]] <= i) { int x = id[j] / m, y = id[j] % m; for (auto [dx, dy]: dxy) { int xx = x + dx, yy = y + dy; if (xx < 0 or xx >= n or yy < 0 or yy >= m) continue; int jj = xx * m + yy; if (rk[jj] > rk[id[j]]) continue; dsu.join(jj, id[j]); } j++; } for (int qid: at[i]) { if (dsu[l[qid]] == dsu[r[qid]]) { hi[qid] = i; } else { lo[qid] = i + 1; } } } } for (int ans: lo) { cout << ans << endl; } } int main() { #ifdef MEGURINE freopen("../input.txt", "r", stdin); freopen("../output.txt", "w", stdout); clock_t start = clock(); #endif ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int T = 1; // cin >> T; cout << fixed << setprecision(12); while (T--) elysia(); #ifdef MEGURINE clock_t end = clock(); cout << "\nRunning Time: " << (double) (end - start) / CLOCKS_PER_SEC * 1000 << "ms" << endl; #endif return 0; }