結果

問題 No.281 門松と魔法(1)
ユーザー lam6er
提出日時 2025-03-20 20:44:45
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,484 bytes
コンパイル時間 171 ms
コンパイル使用メモリ 82,572 KB
実行使用メモリ 82,788 KB
最終ジャッジ日時 2025-03-20 20:44:55
合計ジャッジ時間 7,679 ms
ジャッジサーバーID
(参考情報)
judge2 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 18 TLE * 2 -- * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

def main():
    import sys
    d = int(sys.stdin.readline())
    h1 = int(sys.stdin.readline())
    h2 = int(sys.stdin.readline())
    h3 = int(sys.stdin.readline())

    def is_valid_case1_or_case2(a, b, c):
        if a == b or b == c or a == c:
            return False
        return (b > a and b > c) or (b < a and b < c)

    if d == 0:
        if is_valid_case1_or_case2(h1, h2, h3):
            print(0)
        else:
            print(-1)
        return

    min_ops = float('inf')

    # Case 1: Middle is the tallest
    if h2 >= 1:
        max_k2_case1 = (h2 - 1) // d
        for k2 in range(0, max_k2_case1 + 1):
            H2_candidate = h2 - k2 * d
            if H2_candidate < 1:
                continue
            t = H2_candidate - 1

            # Calculate H1_p and k1
            if h1 <= t:
                k1 = 0
                H1_p = h1
            else:
                required = h1 - t
                k1 = (required + d - 1) // d
                H1_p = max(h1 - k1 * d, 0)
                if H1_p > t:
                    continue

            # Calculate H3_p and k3
            if h3 <= t:
                k3 = 0
                H3_p = h3
            else:
                required = h3 - t
                k3 = (required + d - 1) // d
                H3_p = max(h3 - k3 * d, 0)
                if H3_p > t:
                    continue

            if H1_p != H3_p:
                total = k1 + k2 + k3
                if total < min_ops:
                    min_ops = total

    # Case 2: Middle is the shortest
    t = min(h1 - 1, h3 - 1)
    if t >= 0:
        numerator = h2 - t
        if d == 0:
            k2_min = 0 if h2 <= t else 10**18  # Should not happen as d>0
        else:
            k2_min = max(0, (numerator + d - 1) // d)
        H2_candidate = h2 - k2_min * d
        if H2_candidate >= 0 and H2_candidate <= t:
            cond1 = h1 >= H2_candidate + 1
            cond2 = h3 >= H2_candidate + 1
            if cond1 and cond2:
                valid = True
                if h1 == h3:
                    valid = False
                if H2_candidate == h1 or H2_candidate == h3:
                    valid = False
                if valid and H2_candidate < h1 and H2_candidate < h3:
                    total = k2_min
                    if total < min_ops:
                        min_ops = total

    if min_ops == float('inf'):
        print(-1)
    else:
        print(min_ops)

if __name__ == "__main__":
    main()
0