This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pl;
typedef pair<int,int> pii;
typedef tuple<int,int,int> tt;
#define all(a) a.begin(), a.end()
#define filter(a) a.erase(unique(all(a)), a.end())
const int mn = 4'004'004;
int lo[mn], hi[mn], vec[2][mn], calcLo[mn], calcHi[mn], coor[mn], prod;
int getID (int i, int j) {
return i * 2001 + j;
}
bool check (int arr, int delta) {
int pos = -1, curLo = INT_MAX, curHi = INT_MIN;
for (int k = 0; k < prod; k++) {
int cur = vec[arr][coor[k]];
while (pos + 1 < prod && vec[arr][coor[pos + 1]] < cur - delta) {
pos++;
curLo = min(curLo, lo[coor[pos]]);
curHi = max(curHi, hi[coor[pos]]);
}
if (k + 1 < prod && vec[arr][coor[k]] == vec[arr][coor[k + 1]]) continue;
int cHi = max(calcHi[k], curHi);
int cLo = min(calcLo[k], curLo);
if (cHi == INT_MIN || cHi - cLo <= delta) return 1;
}
return 0;
}
int solve (int arr, int n, int m) {
for (int i = 1; i <= n; i++)
lo[getID(i, 0)] = INT_MAX, hi[getID(i, 0)] = INT_MIN;
for (int j = 1; j <= m; j++) {
int loCol = INT_MAX, hiCol = INT_MIN;
for (int i = n; i >= 1; i--) {
lo[getID(i, j)] = min(lo[getID(i, j - 1)], loCol = min(loCol, vec[arr][getID(i, j)]));
hi[getID(i, j)] = max(hi[getID(i, j - 1)], hiCol = max(hiCol, vec[arr][getID(i, j)]));
}
}
int counter = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
coor[counter++] = getID(i, j);
function<bool(int,int)> comp = [&] (int a, int b) {
return vec[arr][a] < vec[arr][b];
};
sort(coor, coor + prod, comp);
int curLo = INT_MAX, curHi = INT_MIN;
for (int k = prod - 1; k >= 0; k--) {
calcLo[k] = curLo, calcHi[k] = curHi;
curLo = min(curLo, lo[coor[k]]);
curHi = max(curHi, hi[coor[k]]);
}
if (check(arr, 0)) return 0;
int ans = 0;
for (int i = 29; i >= 0; i--)
if (!check(arr, ans | (1 << i))) ans |= (1 << i);
return ans + 1;
}
int getInt() {
int num = 0;
char ch = getchar();
while (ch < '0' || ch > '9') {
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
num = (num << 3) + (num << 1) + (ch - '0');
ch = getchar();
}
return num;
}
int main()
{
int n = getInt(), m = getInt(); prod = n * m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
vec[0][getID(i, j)] = getInt();
vec[1][getID(j, n - i + 1)] = vec[0][getID(i, j)];
}
}
cout << min(solve(0, n, m), solve(1, m, n));
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... |