Advertisement
cincout

Сжатое ДО (Плюс в точке и сумма)

Jul 24th, 2019
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define ll long long
  6.  
  7. struct node
  8. {
  9. node *l, *r;
  10. int key, tl, tr;
  11. node(int _tl, int _tr)
  12. {
  13. l = r = nullptr, key = 0, tl = _tl, tr = _tr;
  14. }
  15. };
  16.  
  17. int get_key(node * a)
  18. {
  19. if (a == nullptr)
  20. return 0;
  21. return a->key;
  22. }
  23.  
  24. void modify(node * cur, int pos, int val)
  25. {
  26. if (cur->tl + 1 == cur->tr)
  27. {
  28. cur->key += val;
  29. return;
  30. }
  31. int m = (cur->tl + cur->tr) / 2;
  32. if (pos < m)
  33. {
  34. if (cur->l == nullptr) cur->l = new node(cur->tl, m);
  35. modify(cur->l, pos, val);
  36. }
  37. else
  38. {
  39. if (cur->r == nullptr) cur->r = new node(m, cur->tr);
  40. modify(cur->r, pos, val);
  41. }
  42. cur->key = get_key(cur->l) + get_key(cur->r);
  43. }
  44.  
  45. int get_sum(node * cur, int l, int r)
  46. {
  47. if (cur == nullptr)
  48. return 0;
  49. if (l <= cur->tl && cur->tr <= r)
  50. {
  51. return cur->key;
  52. }
  53. else if (l >= cur->tr || cur->tl >= r)
  54. {
  55. return 0;
  56. }
  57. int m = (cur->tl + cur->tr) / 2;
  58. return get_sum(cur->l, l, r) + get_sum(cur->r, l, r);
  59. }
  60.  
  61. int main()
  62. {
  63. ios::sync_with_stdio(0);
  64. cin.tie(0);
  65. node * tree = new node(-10, 10);
  66. modify(tree, 0, 3);
  67. modify(tree, -3, 6);
  68. cout << get_sum(tree, -10, 10) << ' ' << get_sum(tree, -3, -2) << '\n';
  69. return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement