This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include<bits/stdc++.h>
#define pb emplace_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
using namespace std;
const int N = int(2e3) + 7;
const int inf = int(1e9) + 7;
int n, m, a[N][N], mn, mx, res;
bool Check(int dif) {
int lim = mn + dif;
if(a[0][0] > lim && a[0][m - 1] > lim) return 0;
int Mx = 0, Mn = inf, h = n;
bool divided;
for(int j = 0; j < m; ++j) {
divided = 0;
if(a[0][j] > lim) h = 0, divided = 1;
for(int i = 0; i < n; ++i) {
if(a[i][j] > lim) divided = 1, h = min(h, i);
else if(i == h) divided = 1;
if(divided) Mx = max(Mx, a[i][j]), Mn = min(Mn, a[i][j]);
}
}
if(Mx - Mn <= dif) return 1;
h = n, Mx = 0, Mn = inf;
for(int j = m - 1; j >= 0; --j) {
divided = 0;
if(a[0][j] > lim) h = 0, divided = 1;
for(int i = 0; i < n; ++i) {
if(a[i][j] <= lim && !divided && i < h) continue;
if(a[i][j] > lim) divided = 1, h = min(h, i);
else if(i == h) divided = 1;
Mx = max(Mx, a[i][j]), Mn = min(Mn, a[i][j]);
divided = 1;
}
}
return Mx - Mn <= dif;
}
void Solve() {
int low, high, mid;
low = 0, high = mx - mn;
while(low <= high) {
mid = (low + high) >> 1;
if(Check(mid)) high = mid - 1;
else low = mid + 1;
}
res = min(res, low);
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
if(fopen("test.inp", "r")) {
freopen("test.inp", "r", stdin);
freopen("test.out", "w", stdout);
}
cin >> n >> m; mn = inf, mx = 0;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
cin >> a[i][j];
mn = min(mn, a[i][j]);
mx = max(mx, a[i][j]);
}
}
res = mx - mn;
Solve();
for(int j = 0; j < m; ++j) {
for(int i = 0; n - 1 - i > i; ++i) {
swap(a[i][j], a[n - 1 - i][j]);
}
}
Solve();
cout << res;
}
Compilation message (stderr)
joioi.cpp: In function 'int main()':
joioi.cpp:60:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)', declared with attribute warn_unused_result [-Wunused-result]
freopen("test.inp", "r", stdin);
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
joioi.cpp:61:16: warning: ignoring return value of 'FILE* freopen(const char*, const char*, FILE*)', declared with attribute warn_unused_result [-Wunused-result]
freopen("test.out", "w", stdout);
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |