#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include template struct DSU { std::vector f, siz; DSU(int n) : f(n), siz(n, 1) { std::iota(f.begin(), f.end(), 0); } T leader(T x) { while (x != f[x]) x = f[x] = f[f[x]]; return x; } bool same(T x, T y) { return leader(x) == leader(y); } bool merge(T x, T y) { x = leader(x); y = leader(y); if (x == y) return false; siz[x] += siz[y]; f[y] = x; return true; } T size(int x) { return siz[leader(x)]; } void clear() { std::fill(siz.begin(), siz.end(), 1); std::iota(f.begin(), f.end(), 0); } }; int main() { int n,m; std::cin >> n >> m; std::vector> g(n, std::vector(m)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { std::cin >> g[i][j]; } } std::vector> edges; auto convert = [&](int x, int y) -> int { return x * m + y; }; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (i + 1 < n) { edges.emplace_back(std::max(g[i][j], g[i + 1][j]), convert(i, j), convert(i + 1,j)); } if (j + 1 < m ) { edges.emplace_back(std::max(g[i][j], g[i][j + 1]), convert(i, j), convert(i, j + 1)); } } } std::sort(edges.begin(), edges.end()); int q; std::cin >> q; std::vector> query(q); for (int i = 0; i < q; i++) { int a,b,c,d; std::cin >> a >> b >> c >> d; a--, b--, c--, d--; query[i] = {a * m + b, c * m + d}; } int k = (int)edges.size(); std::vector r(q, k - 1), l(q, 0); while(true) { bool flag = true; std::vector mid_idx(k, std::vector()); for (int i = 0; i < q; i++) { if (l[i] >= r[i]) continue; flag = false; int mid = (l[i] + r[i]) / 2; mid_idx[mid].push_back(i); } if (flag) break; DSU dsu(k); for (int i = 0; i < k; i++) { auto [w, u, v] = edges[i]; dsu.merge(u, v); for (int idx : mid_idx[i]) { auto [x, y] = query[idx]; if (dsu.same(x, y)) { r[idx] = i; } else { l[idx] = i + 1; } } } } for (int i = 0; i < q; i++) { std::cout << std::get<0>(edges[l[i]]) << std::endl; } }