#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define sz(a) (int)a.size()
#define all(a) begin(a),end(a)
const int N = (int)2e3+10;
int n, m, lst[N];
int dp[N][N], pref[N][N];
int a[N][N], b[N][N], c[N][N];
void Rotate(){
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
swap(b[i][j],b[j][i]);
swap(n,m);
for(int i = 0; i < n; i++)
reverse(b[i],b[i]+m);
}
bool calc(){
for(int k : {0,1}){
memset(dp,0,sizeof(dp));
memset(lst,0,sizeof(lst));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
pref[i][j+1] = pref[i][j]+(!b[i][j] or b[i][j]==k);
if(b[i][j]==k) lst[i]=j+1;
}
}
int bst=-1, bst2;
for(int i = 0; i < n; i++){
bst2=-1;
for(int j = 0; j <= m; j++){
if(pref[i][j]!=j) break;
if(!i) dp[i][j]=(j!=m and j>=lst[i]);
else if(bst!=-1) dp[i][j]=(bst<=j and j>=lst[i]);
if(dp[i][j] and bst2==-1) bst2=j;
}
bst=bst2;
}
bool ok = 0;
for(int i = 1; i <= m; i++) ok|=dp[n-1][i];
if(ok) return 1;
}
return 0;
}
int mn = (int)1e9, mx = 0;
bool chk(int R){
memset(b,0,sizeof(b));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(a[i][j]>mn+R) b[i][j]=2;
if(a[i][j]<mx-R){
if(b[i][j]==2) return 0;
b[i][j] = 1;
}
}
}
bool ok = 0;
for(int i = 0; i < 4; i++)
ok|=calc(), Rotate();
return ok;
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n >> m;
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]);
int l = 0, r = mx-mn;
while(l<r){
int mid = (l+r)/2;
if(chk(mid)) r=mid;
else l=mid+1;
}
cout << l << "\n";
}
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
20 ms |
36176 KB |
Output is correct |
2 |
Incorrect |
21 ms |
36176 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
20 ms |
36176 KB |
Output is correct |
2 |
Incorrect |
21 ms |
36176 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
20 ms |
36176 KB |
Output is correct |
2 |
Incorrect |
21 ms |
36176 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |