Segment tree and Binary Indexed Tree
Segment Tree
Is used in range query problems
Problem 1
Given an array a1,a2,...,an, n≤105, and q≤105 queries (l,r) that asked for the sum ∑ri=lai.
Solution
Create a prefix sum array fi=∑ij=1aj
f1=a1
fi=fi−1+ai
Then ∑ri=lai=fr−fl−1
Overall complexity: O(n+q)
Problem 1 upgraded
There are now 2 types of queries:
- SUM (l,r): asked for the sum ∑ri=lai.
- CHANGE i v: change the value of ai to v
We cannot update f naively after type-2 queries
⇒ We need a data structure called Segment Tree
Create a Segment Tree:
- Each node of the tree manages an interval (l,r)
- Store the sum ∑ri=lai.
- Store the references to node (l,m) and node (m,r) with m=l+r2
Some operations that Segment Tree can do:
- Update the value of an element and the sum of related intervals in O(log2n) time.
- Get the sum of an interval in O(log2n) time
It can be proved that there will be at most 4n nodes in Segment Tree.
Fenwick Tree (Binary Indexed Tree)
A magical tree that uses the properties of the binary representations of numbers.
int updateBIT(int x,int v)
void getBIT(int x)
{
}
Some operations of Binary Indexed Tree
Comparison between Segment Tree (ST) and Binary Indexed Tree (BIT)
In Competitive Programming III
ST:
- Initialization: O(n).
- Update a single point and get an interval operations: O(logn) complexity.
- Can do all types of (l,r) queries
- Drawback: Longer codes, larger constant factor.
- Can use lazy update technique to do range update in O(logn) complexity, as long as you can calculate the new result of an interval based on the information in the query.
BIT:
- Initialization: O(nlogn).
- Drawback: Can only do (1,x) queries ⇒ Cannot find minri=lai because we cannot find minri=lai from minl−1i=1ai and minri=1ai.