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 pair<int, int> pll;
#define all(x) (x).begin(),(x).end()
#define X first
#define Y second
#define sep ' '
#define endl '\n'
#define debug(x) cerr << #x << ": " << x << endl;
const ll MAXN = 2e3 + 10;
int G[MAXN][MAXN], n, m, ans, vis[MAXN][MAXN], mx, mn;
void add_cell(int x, int y, int dx, int dy) {
if (x <= 0 || y <= 0 || x > n || y > m) return;
if (vis[x][y]) return;
vis[x][y] = true;
if (!mn) mn = mx = G[x][y];
mn = min(mn, G[x][y]);
mx = max(mx, G[x][y]);
add_cell(x + dx, y, dx, dy);
add_cell(x, y + dy, dx, dy);
}
inline void solve(int dx, int dy) {
mx = mn = 0;
vector<pair<int, pll>> vec;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
vec.push_back({G[i][j], {i, j}});
vis[i][j] = false;
}
}
sort(all(vec));
ans = min(ans, vec.back().X - vec.front().X);
int l = 0, r = int(vec.size()) - 1;
while (l < r) {
auto [xl, yl] = vec[l].Y;
auto [xr, yr] = vec[r].Y;
if (vis[xl][yl]) {
l++;
continue;
}
if (vis[xr][yr]) {
r--;
continue;
}
add_cell(xl, yl, dx, dy);
while (l <= r) {
auto [xl, yl] = vec[l].Y;
auto [xr, yr] = vec[r].Y;
if (vis[xl][yl]) {
l++;
continue;
}
if (vis[xr][yr]) {
r--;
continue;
}
break;
}
if (l <= r)
ans = min(ans, max(mx - mn, vec[r].X - vec[l].X));
}
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> G[i][j];
}
}
ans = numeric_limits<int>::max();
solve(1, 1);
solve(1, -1);
solve(-1, 1);
solve(-1, -1);
cout << ans << endl;
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... |