結果
問題 | No.366 ロボットソート |
ユーザー |
![]() |
提出日時 | 2025-03-20 21:15:44 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 59 ms / 2,000 ms |
コード長 | 2,255 bytes |
コンパイル時間 | 211 ms |
コンパイル使用メモリ | 82,312 KB |
実行使用メモリ | 68,524 KB |
最終ジャッジ日時 | 2025-03-20 21:16:33 |
合計ジャッジ時間 | 2,203 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 23 |
ソースコード
def main():import sysfrom collections import defaultdictN, K = map(int, sys.stdin.readline().split())a = list(map(int, sys.stdin.readline().split()))original = a.copy()sorted_a = sorted(a)# 1-basedparent = list(range(N + 1)) # parent[0] is unuseddef find(u):while parent[u] != u:parent[u] = parent[parent[u]] # Path compressionu = parent[u]return udef union(u, v):pu = find(u)pv = find(v)if pu != pv:parent[pv] = pufor i in range(1, N + 1):j = i + Kif j <= N:union(i, j)# Check feasibilitypossible = Truefor idx, num in enumerate(sorted_a):j = idx + 1 # 1-basedoriginal_i = original.index(num) + 1 # 1-based index of num in original arrayif find(original_i) != find(j):possible = Falsebreakif not possible:print(-1)return# Collect groupsgroups = defaultdict(list)for i in range(1, N + 1):root = find(i)groups[root].append(i)total_inversions = 0# Function to count inversions using BITdef count_inversions(arr):max_val = max(arr) if arr else 0size = max_val + 2tree = [0] * (size)def update(idx):idx += 1while idx < size:tree[idx] += 1idx += idx & -idxdef query(idx):res = 0idx += 1while idx > 0:res += tree[idx]idx -= idx & -idxreturn resinversions = 0for i in reversed(range(len(arr))):inversions += query(arr[i] - 1)update(arr[i])return inversionsfor group in groups.values():sorted_positions = sorted(group)current_values = [original[pos - 1] for pos in sorted_positions]sorted_values = sorted(current_values)index_map = {v: i for i, v in enumerate(sorted_values)}mapped = [index_map[v] for v in current_values]total_inversions += count_inversions(mapped)print(total_inversions)if __name__ == "__main__":main()