Segment tree and Binary Indexed Tree

Segment Tree

Is used in range query problems

Problem 1

Given an array a1,a2,...,an, n105, and q105 queries (l,r) that asked for the sum ri=lai.

Solution

Create a prefix sum array fi=ij=1aj
f1=a1
fi=fi1+ai

Then ri=lai=frfl1

Overall complexity: O(n+q)

Problem 1 upgraded

There are now 2 types of queries:

We cannot update f naively after type-2 queries
We need a data structure called Segment Tree

Create a Segment Tree:

Some operations that Segment Tree can do:

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: