結果

問題 No.345 最小チワワ問題
ユーザー norioc
提出日時 2025-05-26 03:41:41
言語 PyPy3
(7.3.15)
結果
WA  
実行時間 -
コード長 1,665 bytes
コンパイル時間 483 ms
コンパイル使用メモリ 82,836 KB
実行使用メモリ 66,000 KB
最終ジャッジ日時 2025-05-26 03:41:45
合計ジャッジ時間 3,338 ms
ジャッジサーバーID
(参考情報)
judge3 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 10 WA * 19
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections.abc import Iterable
from enum import IntEnum, auto
from functools import cache


class E(IntEnum):
    S = 0
    C = auto()
    X = auto()
    W1 = auto()
    C_X = auto()
    W2 = auto()
    W1_X = auto()
    G = auto()

    def nexts(self):
        match self:
            case E.S: return [E.C, E.X]
            case E.C: return [E.W1, E.C_X]
            case E.W1: return [E.C, E.W2, E.W1_X]
            case E.W2: return [E.G]
            case E.X: return [E.X, E.C]
            case E.C_X: return [E.C_X, E.C, E.W1]
            case E.W1_X: return [E.W1_X, E.C, E.W2]
            case E.G: return [E.G]

        assert False

    @staticmethod
    @cache
    def states():
        res = []
        for fm in E:
            for to in fm.nexts():
                res.append((fm, to))

        return res


def state_dp(xs: Iterable, op, e, init: dict):
    dp = [e for _ in range(len(E))]
    for k, v in init.items():
        dp[k] = v

    for x in xs:
        pp = [e for _ in range(len(E))]
        dp, pp = pp, dp
        for fm, to in E.states():
            if not is_valid(to, pp[fm], x): continue
            dp[to] = op(to, dp[to], fm, pp[fm], x)

    return dp


def is_valid(to: E, fm_v, v) -> bool:
    if fm_v == INF: return False

    match to:
        case E.C:
            return v == 'c'
        case E.W1 | E.W2:
            return v == 'w'

    return True


def op(to: E, to_v, fm: E, fm_v, v):
    if v == 'c': return 1
    if to == E.G: return min(to_v, fm_v)

    return min(to_v, fm_v + 1)


INF = 1 << 60
S = input()

dp = state_dp(S, op, INF, {E.S: 0})
ans = dp[E.G]
if ans == INF:
    print(-1)
else:
    print(ans)
0