PrevNext
Somewhat Frequent
 0/10

More Applications of Segment Tree

Authors: Benjamin Qi, Andi Qu

Walking on a Segment Tree, Non-Commutative Combiner Functions

Resources
cp-algoFirst two applications and more.

Walking on a Segment Tree

Focus Problem – read through this problem before continuing!

You want to support queries of the following form on an array a1,,aNa_1,\ldots,a_N (along with point updates).

Find the first ii such that aixa_i\ge x.

Of course, you can do this in O(log2N)O(\log^2N) time with a max segment tree and binary searching on the first ii such that max(a1,,ai)x\max(a_1,\ldots,a_i)\ge x. But try to do this in O(logN)O(\log N) time.

Solution - Hotel Queries

Instead of binary searching and querying the segment tree separately, let's do them together!

Assume that you know that the answer is in some range [l,r][l, r]. Let mid=l+r2mid = \left \lfloor{\frac{l + r}{2}}\right \rfloor.

If max(al,,amid)x\max(a_l, \dots, a_{mid}) \geq x, then we know that the answer is in the range [l,mid][l, mid]. Otherwise, the answer is in the range [mid+1,r][mid + 1, r].

Imagine that the segment tree is a decision tree. We start at the root and move down. When we're at some node that contains max(al,,ar)\max(a_l, \dots, a_r) and we know that the answer is in the range [l,r][l, r], we move to the left child if max(al,,amid)x\max(a_l, \dots, a_{mid}) \geq x; otherwise, we move to the right child.

This is convenient because max(al,,amid)\max(a_l, \dots, a_{mid}) is already stored in the left child, so we can find it in O(1)O(1) time.

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 200001;
int n;
int segtree[4 * MAXN], a[MAXN];
void build(int l = 1, int r = n, int node = 1) {
if (l == r) segtree[node] = a[l];

Problems

StatusSourceProblem NameDifficultyTagsSolution
Old GoldNormalExternal Sol
PlatNormalExternal Sol

Non-Commutative Combiner Functions

This section is not complete.

Feel free to file a request to complete this using the "Contact Us" button.

previously only considered commutative operations like sum, max

Focus Problem – read through this problem before continuing!

Focus Problem – read through this problem before continuing!

Solution - Subarray Sum Queries

Solution

Problems

StatusSourceProblem NameDifficultyTagsSolution
Old GoldEasyExternal Sol
Old GoldNormalExternal Sol
POINormalView Solution
PlatHard
Show Tags

PURQ, Greedy

External Sol
Balkan OIHard

Give Us Feedback on More Applications of Segment Tree!

Module Progress:

PrevNext