제출 #1132406

#제출 시각아이디문제언어결과실행 시간메모리
1132406henriessThe Kingdom of JOIOI (JOI17_joioi)C++20
0 / 100
0 ms324 KiB
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>

using namespace std;

int H, W;
vector<vector<int>> altitude;

const int dx[] = {-1, 1, 0, 0};
const int dy[] = {0, 0, -1, 1};

// Check if a cell is within bounds
bool is_valid(int x, int y) {
    return x >= 0 && x < H && y >= 0 && y < W;
}

// Check if we can divide the grid into two regions with maximum altitude difference <= T
bool can_divide(int T) {
    vector<vector<bool>> visited(H, vector<bool>(W, false));
    int regions_count = 0;

    auto bfs = [&](int sx, int sy) {
        queue<pair<int, int>> q;
        q.emplace(sx, sy);
        visited[sx][sy] = true;

        while (!q.empty()) {
            auto [x, y] = q.front();
            q.pop();

            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);
                }
            }
        }
    };

    // Find all connected components
    for (int i = 0; i < H; ++i) {
        for (int j = 0; j < W; ++j) {
            if (!visited[i][j]) {
                ++regions_count;
                bfs(i, j);
                if (regions_count > 2) return false; // Early exit if more than 2 regions
            }
        }
    }

    return regions_count == 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 timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...