bhupixb

Seg tree build update query(max)

Jul 25th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include "bits/stdc++.h"
  2. using namespace std;
  3. const int N = 1e4;
  4. typedef long long int ll;
  5. ll arr[N], tree[N];
  6.  
  7. void build(int l, int r, int idx){
  8. if(l == r){
  9. tree[idx] = arr[l];
  10. return;
  11. }
  12. ll mid = l + r >> 1;
  13. build(1, mid, 2 * idx);
  14. build(mid + 1, r, 2* idx + 1);
  15.  
  16. tree[idx] = max(tree[2 * idx], tree[2 * idx + 1]);
  17. }
  18. void update(int l, int r, int pos, ll val, int idx){
  19. if(l == r && pos == l){
  20. tree[idx] = val;
  21. return ;
  22. }
  23. if(l > pos || pos > r)return;
  24.  
  25. ll mid = (l + r) >> 1;
  26.  
  27. update(l, mid, pos, val, 2 * idx);
  28. update(mid + 1, r, pos, val, 2 * idx + 1);
  29. tree[idx] = max(tree[2 * idx], tree[2 * idx + 1]);
  30.  
  31.  
  32. }
  33. ll query(int l, int r, int ql, int qr, int idx){
  34. if(ql > r || qr < l)return 0;
  35. if(ql <= l && r <= qr)return tree[idx];
  36. ll mid = l + r >> 1;
  37. ll x = query(l, mid, ql, qr, 2 * idx);
  38. ll y = query(mid + 1, r, ql , qr, 2 * idx + 1);
  39. return max(x, y);
  40. }
  41. int main(){
  42. int i, n, q;
  43. cin >> n >> q;
  44. for(i = 1; i <= n; i++)
  45. cin >> arr[i];
  46.  
  47. build(1, n, 1);
  48. cout << tree[1] << endl;
  49. update(1, n, 2, 100, 1);
  50. cout << tree[1] << endl;
  51. while(q--){
  52. int x, y;
  53. cin >> x >> y;
  54. cout << query(1, n, x, y, 1) << endl;
  55. }
  56. return 0;
  57. }
Add Comment
Please, Sign In to add comment