#include <bits/stdc++.h>
using namespace std;
#define pb push_back
const int N=2050;
int n,m,a[N][N];
multiset<int> JOI,IOI;
vector<pair<int,int>> ord;
int ans=-1;
bool was[N][N];
void Upd()
{
if(JOI.empty() || IOI.empty()) return;
int tmp=max(*JOI.rbegin()-*JOI.begin(),*IOI.rbegin()-*IOI.begin());
if(ans==-1 || ans>tmp) ans=tmp;
}
void Solve(vector<pair<int,int>> Move)
{
JOI.clear();
IOI.clear();
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) IOI.insert(a[i][j]),was[i][j]=0;
for(auto p:ord)
{
int x,y;
tie(x,y)=p;
if(!was[x][y])
{
queue<pair<int,int>> q;
auto push=[&](int i, int j)
{
q.push({i,j});
was[i][j]=1;
IOI.erase(IOI.find(a[i][j]));
JOI.insert(a[i][j]);
};
push(x,y);
while(q.size())
{
tie(x,y)=q.front();
q.pop();
for(auto mv:Move)
{
int nx,ny;
nx=x+mv.first;
ny=y+mv.second;
if(nx>=1 && nx<=n && ny>=1 && ny<=m && !was[nx][ny]) push(nx,ny);
}
}
}
Upd();
}
}
int main()
{
scanf("%i %i",&n,&m);
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%i",&a[i][j]),ord.pb({i,j});
sort(ord.begin(),ord.end(),[&](pair<int,int> x, pair<int,int> y){ return a[x.first][x.second]>a[y.first][y.second];});
Solve({{-1,0},{0,-1}});
Solve({{-1,0},{0,1}});
Solve({{1,0},{0,-1}});
Solve({{1,0},{1,0}});
printf("%i\n",ans);
return 0;
}
Compilation message
joioi.cpp: In function 'int main()':
joioi.cpp:54:7: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%i %i",&n,&m);
~~~~~^~~~~~~~~~~~~~~
joioi.cpp:55:66: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%i",&a[i][j]),ord.pb({i,j});
~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
504 KB |
Output is correct |
2 |
Incorrect |
2 ms |
376 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
504 KB |
Output is correct |
2 |
Incorrect |
2 ms |
376 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
2 ms |
504 KB |
Output is correct |
2 |
Incorrect |
2 ms |
376 KB |
Output isn't correct |
3 |
Halted |
0 ms |
0 KB |
- |