結果

問題 No.1604 Swap Sort:ONE
ユーザー lam6er
提出日時 2025-03-26 15:53:00
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 67 ms / 2,000 ms
コード長 939 bytes
コンパイル時間 165 ms
コンパイル使用メモリ 82,240 KB
実行使用メモリ 69,580 KB
最終ジャッジ日時 2025-03-26 15:53:42
合計ジャッジ時間 2,427 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 24
権限があれば一括ダウンロードができます

ソースコード

diff #

class FenwickTree:
    def __init__(self, size):
        self.n = size
        self.tree = [0] * (self.n + 1)
    
    def update(self, idx, delta=1):
        while idx <= self.n:
            self.tree[idx] += delta
            idx += idx & -idx
    
    def query(self, idx):
        res = 0
        while idx > 0:
            res += self.tree[idx]
            idx -= idx & -idx
        return res

n = int(input())
p = list(map(int, input().split()))

# Check if possible (every element can reach its target position)
# Since it's a permutation of 1..N, it's always possible.
# Thus, no need to check for impossibility.

# Calculate the number of inversions
sorted_p = sorted(p)
rank = {v: i+1 for i, v in enumerate(sorted_p)}  # 1-based indexing
compressed = [rank[v] for v in p]

ft = FenwickTree(n)
inv_count = 0

for i in reversed(range(n)):
    inv_count += ft.query(compressed[i] - 1)
    ft.update(compressed[i])

print(inv_count)
0