#include <bits/stdc++.h>
#define int long long
#define fi first
#define se second
#define pii pair <int , int>
#define arr3 array <int , 3>
using namespace std;
const int INF = 1e18;
const int maxn = 2e3 + 7;
int n , m , a[maxn][maxn] , maxval = 0 , b[maxn][maxn];
void rotate() // xoay 90
{
for(int i = 1; i <= m; i++)
{
for(int j = 1; j <= n; j++) b[i][j] = a[n-j+1][i];
}
swap(n , m);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++) a[i][j] = b[i][j];
}
}
bool good(int mid)
{
int last = INF , mx = 0 , mn = INF;
for(int i = 1; i <= n; i++)
{
int j = 0; while(j < m && a[i][j+1] >= maxval - mid) j++;
j = min(j , last);
last = j;
for(int x = j+1; x <= m; x++)
{
mx = max(mx , a[i][x]);
mn = min(mn , a[i][x]);
}
}
return (mx == 0 || mx - mn <= mid);
}
bool check(int mid)
{
bool ans = 0;
ans = max(ans , good(mid)); rotate();
ans = max(ans , good(mid)); rotate();
ans = max(ans , good(mid)); rotate();
ans = max(ans , good(mid)); rotate();
return ans;
}
void solve()
{
cin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
cin >> a[i][j];
maxval = max(maxval , a[i][j]);
}
}
int l = 0 , r = 1e9 , ans = 1e9;
while(l <= r)
{
int mid = (l+r)>>1;
if(check(mid))
{
ans = mid;
r = mid - 1;
}
else l = mid + 1;
}
cout << ans << '\n';
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
solve();
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |