結果

問題 No.1053 ゲーミング棒
ユーザー lam6er
提出日時 2025-03-31 17:56:24
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,623 bytes
コンパイル時間 236 ms
コンパイル使用メモリ 82,288 KB
実行使用メモリ 148,140 KB
最終ジャッジ日時 2025-03-31 17:57:48
合計ジャッジ時間 5,803 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 23 TLE * 1 -- * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys

def main():
    n, *rest = map(int, sys.stdin.read().split())
    a = rest[:n]

    first = {}
    last = {}
    for i in range(n):
        if a[i] not in first:
            first[a[i]] = i
        last[a[i]] = i

    # Check if already valid
    valid = True
    for c in first:
        f = first[c]
        l = last[c]
        for i in range(f, l+1):
            if a[i] != c:
                valid = False
                break
        if not valid:
            break
    if valid:
        print(0)
        return

    # Generate candidates for possible rotation
    candidates = set()
    for c in first:
        pos = last[c] + 1
        if pos > n:
            pos = 0
        candidates.add(pos % n)
    candidates.add(0)

    # Check each candidate
    for k in sorted(candidates):
        # Rotate the array: elements from k to end + start to k-1
        rotated = a[k:] + a[:k]

        # Check each color's continuity in the rotated array
        rot_first = {}
        rot_last = {}
        for i in range(len(rotated)):
            c = rotated[i]
            if c not in rot_first:
                rot_first[c] = i
            rot_last[c] = i

        is_ok = True
        for c in rot_first:
            f = rot_first[c]
            l = rot_last[c]
            for i in range(f, l+1):
                if rotated[i] != c:
                    is_ok = False
                    break
            if not is_ok:
                break
        if is_ok:
            required_ops = 1 if k != 0 else 0
            print(required_ops)
            return

    print(-1)

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