結果
| 問題 |
No.956 Number of Unbalanced
|
| コンテスト | |
| ユーザー |
gew1fw
|
| 提出日時 | 2025-06-12 21:05:39 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 1,719 bytes |
| コンパイル時間 | 242 ms |
| コンパイル使用メモリ | 81,792 KB |
| 実行使用メモリ | 293,472 KB |
| 最終ジャッジ日時 | 2025-06-12 21:07:33 |
| 合計ジャッジ時間 | 4,396 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 6 |
| other | TLE * 1 -- * 23 |
ソースコード
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(int)
for num in a:
freq[num] += 1
total = 0
for x in freq:
B = [1 if num == x else -1 for num in a]
prefix = [0] * (n + 1)
for i in range(n):
prefix[i+1] = prefix[i] + B[i]
# Compress the prefix sums
sorted_ps = sorted(set(prefix))
rank = {v: i for i, v in enumerate(sorted_ps)}
m = len(sorted_ps)
ft = FenwickTree(m)
res = 0
ft.update(rank[prefix[0]])
for i in range(1, n+1):
current = prefix[i]
idx = -1
left, right = 0, m - 1
while left <= right:
mid = (left + right) // 2
if sorted_ps[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()
gew1fw