結果

問題 No.124 門松列(3)
ユーザー Mister
提出日時 2020-08-22 17:37:19
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 4 ms / 5,000 ms
コード長 1,457 bytes
コンパイル時間 1,200 ms
コンパイル使用メモリ 89,464 KB
最終ジャッジ日時 2025-01-13 10:49:00
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <queue>
#include <tuple>

template <class T>
std::vector<T> vec(int len, T elem) { return std::vector<T>(len, elem); }

const std::vector<std::pair<int, int>> dxys{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

bool judge(int a, int b, int c) {
    if (a * b * c == 0) return true;
    return ((a < b && b > c) || (a > b && b < c)) && a != c;
}

void solve() {
    int h, w;
    std::cin >> w >> h;

    auto xss = vec(h, vec(w, 0));
    for (auto& xs : xss) {
        for (auto& x : xs) std::cin >> x;
    }

    auto dist = vec(10, vec(h, vec(w, -1)));
    dist[0][0][0] = 0;
    std::queue<std::tuple<int, int, int>> que;
    que.emplace(0, 0, 0);

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

        for (auto [dx, dy] : dxys) {
            int nx = x + dx,
                ny = y + dy;

            if (nx < 0 || h <= nx ||
                ny < 0 || w <= ny ||
                dist[xss[x][y]][nx][ny] != -1 ||
                !judge(p, xss[x][y], xss[nx][ny])) continue;

            dist[xss[x][y]][nx][ny] = dist[p][x][y] + 1;
            que.emplace(xss[x][y], nx, ny);
        }
    }

    int ans = -1;
    for (auto& ds : dist) {
        int d = ds[h - 1][w - 1];
        if (ans == -1 || (d != -1 && d < ans)) ans = d;
    }

    std::cout << ans << "\n";
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    solve();

    return 0;
}
0