BacHoCuuPikachu

Bird Tree

Sep 12th, 2022
465
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | Source Code | 0 0
  1. // Written by BacHoCuuPikachu
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. struct Bird
  7. {
  8.     int Value; // Minimum value of a segment
  9.     Bird *LeftChild, *RightChild; // Pointers to left child and right child
  10.  
  11.     Bird() // Constructor
  12.     {
  13.         Value = 0;
  14.         LeftChild = NULL;
  15.         RightChild = NULL;
  16.     }
  17.  
  18.     void BirdLay() // Construct Childs
  19.     {
  20.         if (LeftChild == NULL) LeftChild = new Bird();
  21.         if (RightChild == NULL) RightChild = new Bird();
  22.     }
  23. };
  24.  
  25. Bird* Root = new Bird(); // The first Node that manage [1, N]
  26.  
  27. void BirdPerch(Bird *Current, int curL, int curR, int Pos, int newValue)
  28. {
  29.     if (curL > Pos || curR < Pos) { // Pos is not in range [curL, curR]
  30.         return;
  31.     }
  32.  
  33.     if (curL == curR) { // Current is the Node that manage only Posth element
  34.         Current -> Value = newValue;
  35.         return;
  36.     }
  37.  
  38.     int mid = (curL + curR) / 2;
  39.     Current -> BirdLay();
  40.     BirdPerch(Current -> LeftChild, curL, mid, Pos, newValue);
  41.     BirdPerch(Current -> RightChild, mid + 1, curR, Pos, newValue);
  42.     Current -> Value = max(Current -> LeftChild -> Value,
  43.                            Current -> RightChild -> Value);
  44. }
  45.  
  46. int BirdFly(Bird *Current, int curL, int curR, int L, int R)
  47. {
  48.     if (curL > R || curR < L) { // [curL, curR] doesn't intersect with [L, R]
  49.         return 0;
  50.     }
  51.  
  52.     if (L <= curL && curR <= R) { // [curL, curR] is inside [L, R]
  53.         return Current -> Value;
  54.     }
  55.  
  56.     int mid = (curL + curR) / 2;
  57.     Current -> BirdLay();
  58.     return max(BirdFly(Current -> LeftChild, curL, mid, L, R),
  59.                BirdFly(Current -> RightChild, mid + 1, curR, L, R));
  60. }
  61.  
  62.  
  63. int main()
  64. {
  65.     ios_base::sync_with_stdio(false);
  66.     cin.tie(0);
  67.  
  68.     int N, Q;
  69.     cin >> N >> Q;
  70.  
  71.     char Type;
  72.     int Pos, newValue, L, R;
  73.  
  74.     while (Q--) {
  75.         cin >> Type;
  76.         if (Type == 'A') {
  77.             cin >> Pos >> newValue;
  78.             BirdPerch(Root, 1, N, Pos, newValue);
  79.         }
  80.         else { // Type == 'G'
  81.             cin >> L >> R;
  82.             cout << BirdFly(Root, 1, N, L, R) << '\n';
  83.         }
  84.     }
  85. }
Add Comment
Please, Sign In to add comment