Advertisement
_takumi

c6c

Dec 21st, 2022 (edited)
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.08 KB | None | 0 0
  1. #include <cmath>
  2. #include <string>
  3. #include <utility>
  4. #include <iostream>
  5. #include <algorithm>
  6.  
  7. struct Node {
  8.     char color;
  9.     int key;
  10.     struct Node *left;
  11.     struct Node *right;
  12.     struct Node *parent;
  13. };
  14.  
  15. std::pair<bool, int> chk(Node *n) {
  16.     if (n == nullptr) {
  17.         return {true, 1};
  18.     }
  19.     if ((n->left && (n->left->key >= n->key)) || (n->right && (n->right->key <= n->key))) {
  20.         return {false, -1};
  21.     }
  22.     int cnt;
  23.     if (n->color == 'R') {
  24.         cnt = 0;
  25.         if ((n->left && n->left->color == 'R') || (n->right && n->right->color == 'R')) {
  26.             return {false, -1};
  27.         }
  28.     } else {
  29.         cnt = 1;
  30.     }
  31.     std::pair<bool, int> pr = chk(n->right);
  32.     std::pair<bool, int> pl = chk(n->left);
  33.     return {pr.first && pl.first && (pr.second == pl.second), pr.second + cnt};
  34. }
  35.  
  36. bool isBalanced(Node *n) {
  37.     if (n->color == 'R') {
  38.         return false;
  39.     }
  40.     return chk(n).first;
  41. }
  42.  
  43. int main() {
  44.     int n = 0, root_num = 0;
  45.     std::cin >> n;
  46.     if (n == 0) {
  47.         std::cout << "NO\n";
  48.         exit(0);
  49.     }
  50.     std::cin >> root_num;
  51.     auto nodes = new Node *[n + 1];
  52.     for (int i = 1; i < n + 1; ++i) {
  53.         nodes[i] = new Node;
  54.     }
  55.     int number;
  56.     std::string left, right;
  57.     for (int i = 1; i <= n; ++i) {
  58.         std::cin >> number >> nodes[number]->key >> left >> right >> nodes[number]->color;
  59.         if (left != "null") {
  60.             nodes[number]->left = nodes[std::stoi(left)];
  61.             nodes[std::stoi(left)]->parent = nodes[number];
  62.         } else {
  63.             nodes[number]->left = nullptr;
  64.         }
  65.         if (right != "null") {
  66.             nodes[number]->right = nodes[std::stoi(right)];
  67.             nodes[std::stoi(right)]->parent = nodes[number];
  68.         } else {
  69.             nodes[number]->right = nullptr;
  70.         }
  71.     }
  72.     if (isBalanced(nodes[root_num])) {
  73.         std::cout << "YES\n";
  74.     } else {
  75.         std::cout << "NO\n";
  76.     }
  77.     for (int i = 1; i < n + 1; ++i) {
  78.         delete nodes[i];
  79.     }
  80.     delete[] nodes;
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement