#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;
int H, W;
vector<vector<int>> altitude;
// Directions for moving in the grid (up, down, left, right)
const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};
bool is_valid(int x, int y) {
return x >= 0 && x < H && y >= 0 && y < W;
}
// Check if it's possible to divide the grid with the given maximum altitude difference
bool can_divide(int T) {
vector<vector<bool>> visited(H, vector<bool>(W, false));
auto bfs = [&](int sx, int sy, int region) {
queue<pair<int, int>> q;
q.emplace(sx, sy);
visited[sx][sy] = true;
vector<pair<int, int>> cells;
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
cells.emplace_back(x, y);
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (is_valid(nx, ny) && !visited[nx][ny] && abs(altitude[x][y] - altitude[nx][ny]) <= T) {
visited[nx][ny] = true;
q.emplace(nx, ny);
}
}
}
return cells;
};
vector<vector<pair<int, int>>> regions;
for (int i = 0; i < H; ++i) {
for (int j = 0; j < W; ++j) {
if (!visited[i][j]) {
regions.push_back(bfs(i, j, regions.size()));
}
}
}
return regions.size() == 2;
}
int main() {
cin >> H >> W;
altitude.resize(H, vector<int>(W));
int min_alt = INT_MAX, max_alt = INT_MIN;
for (int i = 0; i < H; ++i) {
for (int j = 0; j < W; ++j) {
cin >> altitude[i][j];
min_alt = min(min_alt, altitude[i][j]);
max_alt = max(max_alt, altitude[i][j]);
}
}
int left = 0, right = max_alt - min_alt;
int result = right;
while (left <= right) {
int mid = left + (right - left) / 2;
if (can_divide(mid)) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
cout << result << 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... |