結果

問題 No.13 囲みたい!
ユーザー H3PO4H3PO4
提出日時 2023-02-19 23:01:26
言語 C++17
(gcc 13.2.0 + boost 1.83.0)
結果
AC  
実行時間 6 ms / 5,000 ms
コード長 1,840 bytes
コンパイル時間 1,360 ms
コンパイル使用メモリ 102,664 KB
実行使用メモリ 4,380 KB
最終ジャッジ日時 2023-09-28 02:01:51
合計ジャッジ時間 1,992 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 5 ms
4,380 KB
testcase_04 AC 5 ms
4,380 KB
testcase_05 AC 5 ms
4,376 KB
testcase_06 AC 4 ms
4,376 KB
testcase_07 AC 6 ms
4,380 KB
testcase_08 AC 5 ms
4,380 KB
testcase_09 AC 4 ms
4,380 KB
testcase_10 AC 2 ms
4,380 KB
testcase_11 AC 4 ms
4,376 KB
testcase_12 AC 2 ms
4,376 KB
testcase_13 AC 2 ms
4,376 KB
testcase_14 AC 2 ms
4,376 KB
testcase_15 AC 1 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include<iostream>
#include<vector>
#include<unordered_set>
#include<stack>

bool solve(int W, int H, std::vector<std::vector<int>> M) {
    std::vector<std::vector<int>> G(H * W);
    auto grid2int = [&W](int h, int w) { return h * W + w; };
    for (int h = 0; h < H - 1; h++) {
        for (int w = 0; w < W; w++) {
            if (M.at(h).at(w) == M.at(h + 1).at(w)) {
                G.at(grid2int(h, w)).push_back(grid2int(h + 1, w));
                G.at(grid2int(h + 1, w)).push_back(grid2int(h, w));
            }
        }
    }
    for (int h = 0; h < H; h++) {
        for (int w = 0; w < W - 1; w++) {
            if (M.at(h).at(w) == M.at(h).at(w + 1)) {
                G.at(grid2int(h, w)).push_back(grid2int(h, w + 1));
                G.at(grid2int(h, w + 1)).push_back(grid2int(h, w));
            }
        }
    }
    std::unordered_set<int> nodes;
    for (int i = 0; i < H * W; i++) { nodes.insert(i); }
    while (!nodes.empty()) {
        auto v0 = *nodes.begin();
        nodes.erase(nodes.begin());
        std::stack<std::pair<int, int>> stk;
        stk.emplace(v0, -1);
        while (!stk.empty()) {
            auto [v, p] = stk.top();
            stk.pop();
            nodes.erase(v);
            for (const auto &x: G.at(v)) {
                if (x == p) { continue; }
                if (nodes.find(x) == nodes.end()) {
                    return true;
                }
                stk.emplace(x, v);
            }
        }
    }
    return false;
}

int main() {
    int W, H;
    std::cin >> W >> H;
    std::vector<std::vector<int>> M(H, std::vector<int>(W));
    for (int h = 0; h < H; h++) {
        for (int w = 0; w < W; w++) {
            std::cin >> M.at(h).at(w);
        }
    }
    const std::string ans = solve(W, H, M) ? "possible" : "impossible";
    std::cout << ans << std::endl;
}
0