#include "quality.h"
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define ll long long
#define pii pair<int,int>
#define pli pair<ll,int>
#define pll pair<ll,ll>
#define tiii tuple<int,int,int>
#define tiiii tuple<int,int,int,int>
#define pb push_back
#define eb emplace_back
#define emp emplace
#define mkp make_pair
#define mkt make_tuple
#define vctr vector
#define arr array
#define all(x) x.begin(), x.end()
#define amin(a,b) a = min(a,b)
#define amax(a,b) a = max(a,b)
#define brick(x) cout << #x << " = " << (x) << " | "
#define dbg(x) cout << #x << " = " << (x) << '\n'
#define vdbg(a) cout << #a << " = "; for(auto _x : a)cout << _x << ' '; cout << '\n'
#define adbg(a,n) cout << #a << " = "; for(int _i = 1; _i <= n; ++_i)cout << a[_i] << ' '; cout << '\n'
#define adbg0(a,n) cout << #a << " = "; for(int _i = 0; _i < n; ++_i)cout << a[_i] << ' '; cout << '\n'
mt19937 rng(static_cast<uint32_t>(chrono::steady_clock::now().time_since_epoch().count()));
int uid(int a, int b) { return uniform_int_distribution<int>(a,b)(rng); }
ll uld(ll a, ll b) { return uniform_int_distribution<ll>(a,b)(rng); }
const int MOD = 1e9+7; // 998244353;
int pf[3005][3005];
int a[3005][3005];
int rectangle(int n, int m, int h, int w, int Q[3001][3001]) {
int l = 1, r = n*m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
a[i][j] = Q[i-1][j-1];
}
}
while (l < r) {
int z = l+(r-l)/2;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
pf[i][j] = (a[i][j] <= z ? 1 : -1)+pf[i-1][j]+pf[i][j-1]-pf[i-1][j-1];
}
}
bool check = false;
for (int i = h; i <= n; ++i) {
for (int j = w; j <= m; ++j) {
if (pf[i][j]-pf[i-h][j]-pf[i][j-w]+pf[i-h][j-w] > 0)check = true;
}
}
if (check)r = z;
else l = z+1;
}
return l;
}