結果

問題 No.956 Number of Unbalanced
ユーザー lam6er
提出日時 2025-03-31 17:51:06
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 2,106 bytes
コンパイル時間 151 ms
コンパイル使用メモリ 82,288 KB
実行使用メモリ 54,400 KB
最終ジャッジ日時 2025-03-31 17:52:07
合計ジャッジ時間 4,675 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 6
other TLE * 1 -- * 23
権限があれば一括ダウンロードができます

ソースコード

diff #

class FenwickTree:
    def __init__(self, size):
        self.size = size
        self.tree = [0] * (size + 2)  # Using 1-based indexing, size+2 for safety
    
    def update(self, index, delta=1):
        while index <= self.size:
            self.tree[index] += delta
            index += index & -index
    
    def query(self, index):
        res = 0
        index = min(index, self.size)  # Ensure we don't query beyond the tree size
        while index > 0:
            res += self.tree[index]
            index -= index & -index
        return res

def main():
    import sys
    from collections import defaultdict
    input = sys.stdin.read().split()
    N = int(input[0])
    A = list(map(int, input[1:N+1]))
    freq = defaultdict(int)
    for x in A:
        freq[x] += 1

    total = 0

    for x in freq:
        T = [1 if num == x else -1 for num in A]
        s = [0] * (N + 1)
        for i in range(1, N+1):
            s[i] = s[i-1] + T[i-1]
        
        # Compress s values
        all_s = sorted(set(s))
        compress = {val: idx+1 for idx, val in enumerate(all_s)}  # 1-based index for Fenwick Tree
        max_rank = len(all_s)
        ft = FenwickTree(max_rank)
        res = 0

        ft.update(compress[s[0]])
        for j in range(1, N+1):
            current_s = s[j]
            required = current_s - 1

            # Binary search on all_s for the largest value <= required
            left = 0
            right = len(all_s) - 1
            best = -1
            while left <= right:
                mid = (left + right) // 2
                if all_s[mid] <= required:
                    best = mid
                    left = mid + 1
                else:
                    right = mid - 1
            if best != -1:
                rank = compress[all_s[best]]
                res += ft.query(rank)
            else:
                res += 0

            # Update Fenwick Tree with current_s's rank
            current_rank = compress[current_s]
            ft.update(current_rank)

        total += res

    print(total)

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