#include <bits/stdc++.h>
using namespace std;
#define all(x) x.begin(), x.end()
#define ar array
#define pb push_back
#define ln '\n'
#define size(x) (int)(x).size()
#define int long long
using i64 = long long;
template <class F, class _S>
bool chmin(F &u, const _S &v){
bool flag = false;
if ( u > v ){
u = v; flag |= true;
}
return flag;
}
template <class F, class _S>
bool chmax(F &u, const _S &v){
bool flag = false;
if ( u < v ){
u = v; flag |= true;
}
return flag;
}
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int h, w; cin >> h >> w;
vector <vector<int>> a(h, vector <int> (w));
int mn = 1e9, mx = -mn;
for ( auto &u: a ){
for ( auto &v: u ){
cin >> v;
chmin(mn, v);
chmax(mx, v);
}
}
auto ok = [&](int d){
vector <vector<int>> c(h, vector <int> (w, -1));
for ( int i = 0; i < h; i++ ){
for ( int j = 0; j < w; j++ ){
if ( a[i][j] <= mn + d ){
if ( a[i][j] >= mx - d ){
continue;
}
c[i][j] = 0;
} else{
if ( mx - d > a[i][j] ) return false;
c[i][j] = 1;
}
}
}
for ( auto x: {0, 1} ){
int prv = -1, flag = true;
for ( int i = 0; i < h; i++ ){
int lst = prv, y = w;
for ( int j = 0; j < w; j++ ){
if ( c[i][j] == -1 ) continue;
if ( c[i][j] == x ){
chmax(lst, j);
} else chmin(y, j);
}
if ( y <= lst ) flag = false;
swap(prv, lst);
}
if ( flag ) return true;
}
for ( auto x: {0, 1} ){
int prv = -1, flag = true;
for ( int i = h - 1; i >= 0; i-- ){
int lst = prv, y = w;
for ( int j = 0; j < w; j++ ){
if ( c[i][j] == -1 ) continue;
if ( c[i][j] == x ){
chmax(lst, j);
} else chmin(y, j);
}
if ( y <= lst ) flag = false;
swap(prv, lst);
}
if ( flag ) return true;
}
return false;
};
int l = 0, r = 1e9;
while ( l < r ){
int m = (l + r) / 2;
if ( ok(m) ) r = m;
else l = m + 1;
}
cout << l;
cout << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |