結果

問題 No.505 カードの数式2
ユーザー norioc
提出日時 2025-06-21 16:32:00
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 53 ms / 2,000 ms
コード長 1,931 bytes
コンパイル時間 415 ms
コンパイル使用メモリ 82,168 KB
実行使用メモリ 63,364 KB
最終ジャッジ日時 2025-06-21 16:32:03
合計ジャッジ時間 3,177 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

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


class E(IntEnum):
    S = 0
    ADD = auto()
    SUB = auto()
    MUL = auto()
    DIV = auto()

    def nexts(self):
        match self:
            case E.S: return [E.ADD, E.SUB, E.MUL, E.DIV]
            case E.ADD: return [E.ADD, E.SUB, E.MUL, E.DIV]
            case E.SUB: return [E.ADD, E.SUB, E.MUL, E.DIV]
            case E.MUL: return [E.ADD, E.SUB, E.MUL, E.DIV]
            case E.DIV: return [E.ADD, E.SUB, E.MUL, E.DIV]

        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] * len(E)
    for k, v in init.items():
        dp[k] = v

    for x in xs:
        pp = [e] * 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
    if to == E.DIV and v == 0: return False

    return True


def get_value(to: E, fm_v, v):
    match to:
        case E.ADD:
            return fm_v + v
        case E.SUB:
            return fm_v - v
        case E.MUL:
            return fm_v * v
        case E.DIV:
            sgn = -1 if fm_v * v < 0 else 1
            return sgn * (abs(fm_v) // abs(v))

    assert False


def op(to: E, to_v, fm: E, fm_v, v):
    a = get_value(to, fm_v[0], v)
    b = get_value(to, fm_v[1], v)

    mi = min(to_v[0], a, b)
    ma = max(to_v[1], a, b)
    return mi, ma


INF = 1 << 60
N = int(input())
A = list(map(int, input().split()))

inf = (INF, -INF)  # (min, max)
dp = state_dp(A[1:], op, inf, {E.S: (A[0], A[0])})
ans = max(dp[x][1] for x in [E.ADD, E.SUB, E.MUL, E.DIV])
print(ans)
0