結果

問題 No.956 Number of Unbalanced
ユーザー lam6er
提出日時 2025-04-15 22:16:26
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,870 bytes
コンパイル時間 957 ms
コンパイル使用メモリ 81,812 KB
実行使用メモリ 294,936 KB
最終ジャッジ日時 2025-04-15 22:18:43
合計ジャッジ時間 4,315 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 6
other TLE * 1 -- * 23
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import defaultdict

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

def main():
    input = sys.stdin.read().split()
    n = int(input[0])
    a = list(map(int, input[1:n+1]))
    
    freq = defaultdict(list)
    for i, num in enumerate(a):
        freq[num].append(i)
    
    total = 0
    
    for x in freq:
        B = [0] * n
        for i in range(n):
            B[i] = 1 if a[i] == x else -1
        
        prefix = [0] * (n + 1)
        for i in range(n):
            prefix[i+1] = prefix[i] + B[i]
        
        # Coordinate compression
        sorted_prefix = sorted(set(prefix))
        rank = {v: i for i, v in enumerate(sorted_prefix)}
        m = len(sorted_prefix)
        
        ft = FenwickTree(m)
        res = 0
        ft.update(rank[prefix[0]])
        
        for i in range(1, n+1):
            current = prefix[i]
            # Find the number of elements < current
            idx = -1
            left, right = 0, m-1
            while left <= right:
                mid = (left + right) // 2
                if sorted_prefix[mid] < current:
                    idx = mid
                    left = mid + 1
                else:
                    right = mid - 1
            if idx != -1:
                res += ft.query(idx)
            ft.update(rank[current])
        
        total += res
    
    print(total)

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