@@ -385,30 +385,19 @@ 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
390
```{.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);
391
+ int get_first(int v, int tl, int tr, int l, int r, int x) {
392
+ if(tl > r || tr < l) return -1;
393
+ if(t[v] <= x) return -1;
394
+
395
+ if (tl== tr) return tl;
396
+
397
+ int tm = tl + (tr-tl)/2;
398
+ int left = get_first(2*v, tl, tm, l, r, x);
399
+ if(left != -1) return left;
400
+ return get_first(2*v+1, tm+1, tr, l ,r, x);
412
401
}
413
402
```
414
403
0 commit comments