結果

問題 No.694 square1001 and Permutation 3
ユーザー lam6er
提出日時 2025-04-15 23:59:20
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 1,397 ms / 3,000 ms
コード長 1,449 bytes
コンパイル時間 229 ms
コンパイル使用メモリ 81,788 KB
実行使用メモリ 195,676 KB
最終ジャッジ日時 2025-04-16 00:01:14
合計ジャッジ時間 9,943 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 13
権限があれば一括ダウンロードができます

ソースコード

diff #

import bisect

class FenwickTree:
    def __init__(self, size):
        self.n = size
        self.tree = [0] * (self.n + 2)  # 1-based indexing

    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

def main():
    import sys
    input = sys.stdin.read().split()
    ptr = 0
    N = int(input[ptr])
    ptr += 1
    A = []
    for _ in range(N):
        A.append(int(input[ptr]))
        ptr += 1

    # Compute inversion count C0
    sorted_arr = sorted(A)
    max_rank = len(sorted_arr)
    ft = FenwickTree(max_rank)
    C0 = 0
    for x in reversed(A):
        r = bisect.bisect_left(sorted_arr, x) + 1  # 1-based rank
        C0 += ft.query(r - 1)
        ft.update(r)

    # Compute count_less and count_greater for each element
    count_less = []
    count_greater = []
    for x in A:
        less = bisect.bisect_left(sorted_arr, x)
        greater = len(sorted_arr) - bisect.bisect_right(sorted_arr, x)
        count_less.append(less)
        count_greater.append(greater)

    # Compute all C_i
    C = [0] * N
    C[0] = C0
    for i in range(1, N):
        C[i] = C[i-1] - count_less[i-1] + count_greater[i-1]

    # Output the results
    for c in C:
        print(c)

if __name__ == '__main__':
    main()
0