Advertisement
Guest User

Segtree-Style Binary Search

a guest
Jul 21st, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. struct Segtree //max with binary searching
  2. {
  3.     ll tr[4000001];
  4.    
  5.     void build(int lo, int hi, int cur)
  6.     {
  7.         if (lo == hi)
  8.         {
  9.             tr[cur] = pre[lo];
  10.             return;
  11.         }
  12.         int mid = (lo+hi)/2;
  13.         build(lo, mid, cur*2);
  14.         build(mid+1, hi, cur*2+1);
  15.         tr[cur] = max(tr[cur*2], tr[cur*2+1]);
  16.     }
  17.    
  18.     void build() { build(1, n, 1); }
  19.    
  20.     int find(ll k, int lo, int hi, int cur) //find lowest pos such that a[pos] >= k
  21.     {
  22.         if (lo == hi && tr[cur] >= k) return lo;
  23.         int mid = (lo+hi)/2;
  24.         if (tr[cur*2] >= k) return find(k, lo, mid, cur*2); //prioritize left (lower index)
  25.         else if (tr[cur*2+1] >= k) return find(k, mid+1, hi, cur*2+1);
  26.         else return -1;
  27.     }
  28.    
  29.     int find(ll k) { return find(k, 1, n, 1); } //logn
  30.    
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement