Skip to content

Commit e4b572c

Browse files
authored
Resolving issue cp-algorithms#915
Attempt to resolve issue cp-algorithms#915. Added additional explanation on how to use. Wondered if making arguments than don't change constant makes more sense? Formatted code more similarly to previous versions of segment tree.
1 parent 86b1324 commit e4b572c

1 file changed

Lines changed: 12 additions & 22 deletions

File tree

src/data_structures/segment_tree.md

Lines changed: 12 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -385,30 +385,20 @@ However, this will lead to a $O(\log^2 n)$ solution.
385385
386386
Instead, we can use the same idea as in the previous sections, and find the position by descending the tree:
387387
by moving each time to the left or the right, depending on the maximum value of the left child.
388-
Thus finding the answer in $O(\log n)$ time.
388+
Thus finding the answer in $O(\log n)$ time.
389389
390+
An example of using the following code would be get_first(1,0,n-1,5,8,14) since our segment tree starts at node 1. This would request a value greater than 14 between $[5,8]$.
390391
```{.cpp file=segment_tree_first_greater}
391-
int get_first(int v, int lv, int rv, int l, int r, int x) {
392-
if(lv > r || rv < l) return -1;
393-
if(l <= lv && rv <= r) {
394-
if(t[v] <= x) return -1;
395-
while(lv != rv) {
396-
int mid = lv + (rv-lv)/2;
397-
if(t[2*v] > x) {
398-
v = 2*v;
399-
rv = mid;
400-
}else {
401-
v = 2*v+1;
402-
lv = mid+1;
403-
}
404-
}
405-
return lv;
406-
}
407-
408-
int mid = lv + (rv-lv)/2;
409-
int rs = get_first(2*v, lv, mid, l, r, x);
410-
if(rs != -1) return rs;
411-
return get_first(2*v+1, mid+1, rv, l ,r, x);
392+
int get_first(int v, int tl, int tr, int l, int r, int greater_than) {
393+
if(tl > r || tr < l) return -1;
394+
if(t[v] <= greater_than) return -1;
395+
396+
if (tl== tr) return tl;
397+
398+
int tm = tl + (tr-tl)/2;
399+
int left = get_first(2*v, tl, tm, l, r, greater_than);
400+
if(left != -1) return left;
401+
return get_first(2*v+1, tm+1, tr, l ,r, greater_than);
412402
}
413403
```
414404

0 commit comments

Comments
 (0)