Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL for segment tree in C++

Is there any STL for segment tree?

In competitive programming it takes a lot of time to code for seg tree. I wonder if there is any STL for that so that lot of time could be saved.

like image 335
Ankita Singh Avatar asked Feb 16 '15 05:02

Ankita Singh


People also ask

How do you code a segment tree?

Construction of Segment Tree from the given array: We start with a segment arr[0 . . . n-1]. and every time we divide the current segment into two (if it has not yet become a segment of length 1), and then call the same procedure on both halves, and for each such segment, we store the sum in the corresponding node.

What is query in segment tree?

Segment tree can be used to do preprocessing and query in moderate time. With a segment tree, preprocessing time is O(n) and the time complexity for a range minimum query is O(Logn). The extra space required is O(n) to store the segment tree.

Why size of segment tree is 4 * n?

The height of the segment tree is O(log n) because while moving from the root to the leaves at every level, the length of the segments is reduced by half. The total number of nodes involved in the segment tree is 4*n.

How do you calculate the size of a segment tree?

Size of the Array Used in Segment Tree Representation If the size of the input array is of power 2, then there are no dummy nodes. Thus, the size of the segment tree is (2 * n - 1), where n is the size of the input array. It is because the total number of leaf nodes will be s, and internal nodes will be n - 1.


1 Answers

I assume by "segment tree" you actually mean range tree, which is more commonly used in programming contests than the more specialized structure for storing a set of intervals.

There is no such container in the C++ standard library but if you are competing in ACM contests you can consider writing your own and simply copying it as needed. You can find my own implementation here (including lazy propagation) but if you search the web you can probably find a more generic version.

In applications where you need the sum instead of the minimum or maximum, you can use a binary indexed tree instead of a segment tree, which is faster, uses less memory, and is also easier to code (about a dozen lines or less).

like image 55
Brian Bi Avatar answered Oct 06 '22 00:10

Brian Bi