#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 600005
#define pb push_back
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
#define sz(s) (int)s.size()
#define pii pair<int,int>
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ll n, a[2000][2000], t, m, b[N], answer, tt;
vector <pair<ll,ll>> v, ans;
void solve(int x) {
if(x == tt + 1) {
ans.clear();
for(int i = 1; i <= tt; i++) {
if(b[i]) ans.pb({v[i - 1].ff,v[i - 1].ss});
}
if(sz(ans)) {
sort(ans.begin(),ans.end());
ll mn = a[ans[0].ff][ans[0].ss], mx = a[ans[0].ff][ans[0].ss];
for(int i = 0;i<sz(ans) - 1; i++) {
if(abs(ans[i + 1].ff - ans[i].ff) + abs(ans[i + 1].ss - ans[i].ss) > 1) return;
mn = min(a[ans[i].ff][ans[i].ss],mn);
mx = max(mx,a[ans[i].ff][ans[i].ss]);
mn = min(a[ans[i+1].ff][ans[i + 1].ss],mn);
mx = max(mx,a[ans[i+1].ff][ans[i+1].ss]);
}
t = sz(ans);
answer = max(answer,mx - mn - t);
}
return;
}
b[x] = 0;
solve(x+1);
b[x] = 1;
solve(x+1);
}
int main () {
ios::sync_with_stdio(0);cin.tie(0);
cin >> n >> m;
for(int i = 1;i <= n;i++) {
for(int j = 1;j <=m;j++) {
cin >> a[i][j];
if(n*m <= 20) v.pb({i,j});
}
}
tt = sz(v);
if(n * m <= 20) {
solve(1);
cout << answer << '\n';
return 0;
}
for(int i = 1; i <= m; i++) {
ll mn = a[1][i], mx = a[1][i];
for(int j = i + 1; j <= m; j++) {
mx = max(mx,a[1][j]);
mn = min(mn,a[1][j]);
answer = max(answer, mx - mn - (j - i + 1));
}
}
cout << answer << '\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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |