結果

問題 No.1053 ゲーミング棒
ユーザー lam6er
提出日時 2025-03-26 15:58:54
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 139 ms / 2,000 ms
コード長 1,632 bytes
コンパイル時間 171 ms
コンパイル使用メモリ 82,644 KB
実行使用メモリ 123,692 KB
最終ジャッジ日時 2025-03-26 15:59:45
合計ジャッジ時間 3,872 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 34
権限があれば一括ダウンロードができます

ソースコード

diff #
プレゼンテーションモードにする

import sys
from collections import defaultdict
def main():
N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))
count = defaultdict(int)
last = {}
for i in range(N):
c = A[i]
count[c] += 1
last[c] = i # 0-based
# Sort colors based on their last occurrence
sorted_colors = sorted(last.keys(), key=lambda x: last[x])
# Construct the target array T
T = []
for c in sorted_colors:
T.extend([c] * count[c])
if T == A:
print(0)
return
# Check if T is a cyclic shift of A (i.e., exists in A + A)
s = A + A
pattern = T
len_pat = len(pattern)
len_text = len(s)
# KMP algorithm to check if pattern is a substring of s
# Build prefix array (LPS)
lps = [0] * len_pat
length = 0 # length of the previous longest prefix suffix
i = 1
while i < len_pat:
if pattern[i] == pattern[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
# Search using KMP
i = j = 0
found = False
while i < len_text:
if s[i] == pattern[j]:
i += 1
j += 1
if j == len_pat:
found = True
break
else:
if j != 0:
j = lps[j - 1]
else:
i += 1
if found:
print(1)
else:
print(-1)
if __name__ == "__main__":
main()
הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
0