1. 程式人生 > 其它 >Advanced Data Structure 樹狀陣列

Advanced Data Structure 樹狀陣列

樹狀陣列

更高效地對點、區間進行查詢、更新

ref:樹狀陣列詳解

k為i的二進位制中從低位到高位的連續零長度

C[i] = A[i-2k+1] +A[i-2k+2] + ... + A[i]

2k = i&(-i)

sum[i] = C[i] + C[i - 2k1] +C[i - 2k1 - 2k2]

eg:315. 計算右側小於當前元素的個數

def lowBit(x:int) -> int:
    return x&(-x)

def update(x: int, n: int, y: int, c:[]):
     i = x
     while
i < n: c[i] += y i += lowBit(i) def getSum(x: int, c:[]) -> int: ans = 0 i = x while i > 0: ans += c[i] i -= lowBit(i) return ans class Solution: def countSmaller(self, nums:[int]) ->[int]: buckets = set() for num in nums: buckets.add(num) buckets
= sorted(buckets) pos = {} for i, e in enumerate(list(buckets)): pos[e] = i n = len(nums) counts = [0] * n c = [0] * n for i in range(n - 1, -1, -1): id = pos[nums[i]] + 1 update(id, n, 1, c) counts[i] = getSum(id - 1, c)
return counts