Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- struct SimpleRBNode {
- int value;
- int left;
- int right;
- bool isBlack;
- };
- class ArrayRBTree {
- public:
- ArrayRBTree(int size, int root) {
- array_tree_ = new SimpleRBNode[size + 1];
- root_index_ = root;
- array_tree_[0] = SimpleRBNode{0, -1, -1, true};
- bst_ = new int[size];
- index_ = 0;
- }
- ~ArrayRBTree() {
- delete[] array_tree_;
- delete[] bst_;
- }
- void add(const SimpleRBNode& rb_node, int index) {
- array_tree_[index] = rb_node;
- }
- bool checkRbTree() {
- int result = dfsBlackCount(root_index_);
- bool is_rb = dfs(root_index_, 0);
- bool is_bst = true;
- for (int i = 1; i < index_; ++i) {
- if (bst_[i] <= bst_[i - 1]) {
- is_bst = false;
- break;
- }
- }
- return array_tree_[root_index_].isBlack && is_rb && result != -1 && is_bst;
- }
- private:
- bool dfs(int node, int parent) {
- if (node == 0) {
- return array_tree_[node].isBlack;
- }
- if (!array_tree_[node].isBlack && !array_tree_[parent].isBlack) {
- return false;
- }
- bool left = dfs(array_tree_[node].left, node);
- bst_[index_++] = array_tree_[node].value;
- bool right = dfs(array_tree_[node].right, node);
- return left && right;
- }
- int dfsBlackCount(int node) {
- if (node == 0) {
- return 0;
- }
- int count_left = dfsBlackCount(array_tree_[node].left);
- int count_right = dfsBlackCount(array_tree_[node].right);
- if (count_left >= 0 && count_right >= 0 && count_left == count_right) {
- return count_left + (array_tree_[node].isBlack ? 1 : 0);
- } else {
- return -1;
- }
- }
- SimpleRBNode* array_tree_;
- int root_index_;
- int* bst_;
- int index_;
- };
- void parse(ArrayRBTree* tree) {
- int index, value;
- std::cin >> index >> value;
- std::string left_child, right_child, color;
- std::cin >> left_child >> right_child >> color;
- SimpleRBNode node{value, left_child == "null" ? 0 : stoi(left_child),
- right_child == "null" ? 0 : stoi(right_child), color == "B"};
- tree->add(node, index);
- }
- int execute(int size, int root) {
- ArrayRBTree array_tree(size, root);
- for (int i = 0; i < size; ++i) {
- parse(&array_tree);
- }
- std::cout << (array_tree.checkRbTree() ? "YES" : "NO");
- return 0;
- }
- void fastIO() {
- std::ios_base::sync_with_stdio(false);
- std::cin.tie(nullptr);
- std::cout.tie(nullptr);
- }
- int main(int argc, char** argv) {
- fastIO();
- int size, root;
- std::cin >> size;
- if (size == 0) {
- std::cout << "YES";
- return 0;
- }
- std::cin >> root;
- return execute(size, root);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement