結果

問題 No.956 Number of Unbalanced
ユーザー lam6er
提出日時 2025-04-16 15:53:00
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,076 bytes
コンパイル時間 261 ms
コンパイル使用メモリ 82,296 KB
実行使用メモリ 295,596 KB
最終ジャッジ日時 2025-04-16 15:53:51
合計ジャッジ時間 4,332 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
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  # 1-based indexing
        while idx <= self.n:
            self.tree[idx] += delta
            idx += idx & -idx
    
    def query(self, idx):
        idx += 1  # 1-based indexing
        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(int)
    for num in A:
        freq[num] += 1
    
    answer = 0
    
    for x in freq:
        B = []
        for num in A:
            if num == x:
                B.append(1)
            else:
                B.append(-1)
        
        prefix = [0] * (n + 1)
        for i in range(1, n+1):
            prefix[i] = prefix[i-1] + B[i-1]
        
        # Compress prefix sums
        all_s = list(prefix)
        sorted_s = sorted(set(all_s))
        rank = {v: i for i, v in enumerate(sorted_s)}
        m = len(sorted_s)
        
        ft = FenwickTree(m)
        s0 = prefix[0]
        ft.update(rank[s0])
        
        current = 0
        for i in range(1, n+1):
            s = prefix[i]
            # Find the number of elements < s in prefix[0..i-1]
            # Find the largest index in sorted_s that is < s
            left, right = 0, m-1
            pos = -1
            while left <= right:
                mid = (left + right) // 2
                if sorted_s[mid] < s:
                    pos = mid
                    left = mid + 1
                else:
                    right = mid -1
            if pos != -1:
                current += ft.query(pos)
            else:
                current += 0
            # Update the Fenwick tree with the current s
            ft.update(rank[s])
        
        answer += current
    
    print(answer)

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