結果
問題 | No.1053 ゲーミング棒 |
ユーザー |
![]() |
提出日時 | 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 |
ソースコード
import sysfrom collections import defaultdictdef 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] += 1last[c] = i # 0-based# Sort colors based on their last occurrencesorted_colors = sorted(last.keys(), key=lambda x: last[x])# Construct the target array TT = []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 + Apattern = Tlen_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_patlength = 0 # length of the previous longest prefix suffixi = 1while i < len_pat:if pattern[i] == pattern[length]:length += 1lps[i] = lengthi += 1else:if length != 0:length = lps[length - 1]else:lps[i] = 0i += 1# Search using KMPi = j = 0found = Falsewhile i < len_text:if s[i] == pattern[j]:i += 1j += 1if j == len_pat:found = Truebreakelse:if j != 0:j = lps[j - 1]else:i += 1if found:print(1)else:print(-1)if __name__ == "__main__":main()