You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Copy file name to clipboardExpand all lines: src/data_structures/segment_tree.md
+12-22Lines changed: 12 additions & 22 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -385,30 +385,20 @@ However, this will lead to a $O(\log^2 n)$ solution.
385
385
386
386
Instead, we can use the same idea as in the previous sections, and find the position by descending the tree:
387
387
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.
389
389
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]$.
390
391
```{.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);
0 commit comments