結果

問題 No.366 ロボットソート
コンテスト
ユーザー Đức Minh Vũ
提出日時 2026-02-10 17:04:35
言語 Python3
(3.14.3 + numpy 2.4.2 + scipy 1.17.0)
コンパイル:
python3 -mpy_compile _filename_
実行:
python3 _filename_
結果
WA  
実行時間 -
コード長 1,030 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 689 ms
コンパイル使用メモリ 20,812 KB
実行使用メモリ 15,612 KB
最終ジャッジ日時 2026-02-10 17:04:41
合計ジャッジ時間 5,059 ms
ジャッジサーバーID
(参考情報)
judge4 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 15 WA * 8
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys
sys.setrecursionlimit(10**7)

n, k = map(int, input().split())
a = list(map(int, input().split()))

b = sorted(a)

ans = 0

for i in range(k):
    cur = []
    need = []
    
    j = i
    while j < n:
        cur.append(a[j])
        need.append(b[j])
        j += k
    
    if sorted(cur) != sorted(need):
        print(-1)
        sys.exit()
    
    # tạo mapping value -> list vị trí trong need
    from collections import defaultdict, deque
    
    pos = defaultdict(deque)
    for idx, val in enumerate(need):
        pos[val].append(idx)
    
    # xây permutation
    perm = []
    for val in cur:
        perm.append(pos[val].popleft())
    
    # đếm cycle
    visited = [False]*len(perm)
    
    for j in range(len(perm)):
        if visited[j]:
            continue
        
        cycle = 0
        x = j
        
        while not visited[x]:
            visited[x] = True
            x = perm[x]
            cycle += 1
        
        if cycle > 1:
            ans += cycle - 1

print(ans)
0