Counting Inversions
Given A[1, n] of n distinct integers, count number of inversions
Θ(nlogn) time with BIT
Nested Segments
Given n segments [Li, Ri], for each segment, find the number of segments that are completely contained in the segment. There are no overlapping endpoints.
Θ(nlogn) time with BIT
Update the array
Given A[1, n] initialized to zero, we would like to support
* Access(i) returns A[i]
* RangeUpdate (l, r, v) adds v to A[l], A[l+1], … , A[r]
Goal: queries in Θ(logn) time
Use a vector B (with Fenwick Tree) such that Sum(i) = Access(i) = A[i]
Θ(logn) time with BIT
Dynamic Prefix Sums with Range Updates
Given A[1, n] initialized to zero, we would like to support
* Sum(i) returns prefix sums of A[i]
* Add(i, v) performs A[i] += v
* RangeUpdate (l, r, v) adds v to A[l], A[l+1], … , A[r]
Goal: queries in Θ(logn) time
Add(i, v) = RangeUpdate(i, i, v)
Access(i) = Sum(i) - Sum(i - 1)
Store two Fenwick Trees, FT1 and FT2.
FT1 such that Sum(i) = A[i], which means that RangeUpdate (l, r, v) performs Add(l, v) and Add(r+1, -v).
SumFT1(i) * i will give some errors, use FT2 to cancel out.
FT2[l] = -v(l-1)
FT2[r+1] = v(l-1) + v(r-l+1)
Finally, Sum(i) = SumFT1(i) * i + SumFT2(i)
Fenwick Tree