#include<bits/stdc++.h>
#define f first
#define int long long
#define s second
using namespace std;
const int N=2e3+5,mod=1e9+7;
int t,a[N][N],r[N],l[N],mn[N],mx[N],n,m,ans;
map<int,int> fix;
vector<int> val;
string s;
bool check(int mx1){
int diff=mx1-val[0];
for(int i=1;i<=n;i++) {
l[i]=m+1; r[i]=0;
}
for(int i=1;i<=n;i++) {
for(int j=m;j>=1;j--){
if(a[i][j]>mx1) l[i] = j - 1;
}
for(int j=1;j<=m;j++){
if(a[i][j]+diff<val.back()) r[i] = j + 1;
}
}
int Mn = m,Mx = 0;
mn[n+1] = m; mx[n+1] = m;
for(int i=n;i>=1;i--){
mn[i]=min(mn[i],r[i]);
mx[i]=max(mx[i],mx[i]);
}
for(int i=1;i<=n;i++){
if(r[i] > l[i]+1) return 0;
Mn=min(Mn,l[i]);
Mx=max(Mx,r[i]);
if(l[i] == 0 && (mn[i]|| Mn)) return 0;
if(r[i] == m + 1 && (mx[i]!=m+1 || Mx!=m+1)) return 0;
}
return 1;
}
void search(){
int l = 0,r =(int)val.size()-1;
while(l<=r){
int mid=(l+r)/2;
if(check(val[mid])) {
ans =min(ans, (val[mid]-val[0]));
r=mid-1;
}
else l=mid+1;
}
}
bool check2(int mn1){
int diff=val.back()-mn1;
for(int i=1;i<=n;i++) {
l[i]=m+1; r[i]=0;
}
for(int i=1;i<=n;i++) {
for(int j=m;j>=1;j--){
if(a[i][j]<mn1) l[i] = j - 1;
}
for(int j=1;j<=m;j++){
if(a[i][j]-diff>val[0]) r[i] = j + 1;
}
}
int Mn = m,Mx = 0;
mn[n+1] = m; mx[n+1] = m;
for(int i=n;i>=1;i--){
mn[i]=min(mn[i],r[i]);
mx[i]=max(mx[i],mx[i]);
}
for(int i=1;i<=n;i++){
if(r[i] > l[i]+1) return 0;
Mn=min(Mn,l[i]);
Mx=max(Mx,r[i]);
if(l[i] == 0 && (mn[i]|| Mn)) return 0;
if(r[i] == m + 1 && (mx[i]!=m+1 || Mx!=m+1)) return 0;
}
return 1;
}
void search2(){
int l = 0,r =(int)val.size()-1;
while(l<=r){
int mid=(l+r)/2;
if(check2(val[mid])) {
ans = min(ans,(-val[mid]+val.back()));
l=mid+1;
}
else r=mid-1;
}
}
main(){
// t=1;
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin >> a[i][j];
if(!fix[a[i][j]]) val.push_back(a[i][j]);
fix[a[i][j]]=1;
}
}
sort(val.begin(),val.end());
ans = val.back()-val[0];
search();
search2();
for(int i=1;i<=n;i++){
for(int j=1;j<=m/2;j++){
swap(a[i][j],a[i][m-j+1]);
}
}
search();
search2();
cout<<ans;
}
Compilation message
joioi.cpp:92:7: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
92 | main(){
| ^
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
332 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
332 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Incorrect |
1 ms |
332 KB |
Output isn't correct |
2 |
Halted |
0 ms |
0 KB |
- |