#include
struct Node {
long data;
long height;
Node* left;
Node* right;
};
struct AVL {
Node* top = nullptr;
long height(Node* root) {
if (root == nullptr)
return 0;
return root->height;
}
Node* newNode(long value) {
Node* root = new Node();
root->data = value;
root->left = nullptr;
root->right = nullptr;
root->height = 1;
return(root);
}
Node* RightRotation(Node* y) {
Node* x = y->left;
Node* T2 = x->right;
x->right = y;
y->left = T2;
y->height = std::max(height(y->left), height(y->right)) + 1;
x->height = std::max(height(x->left), height(x->right)) + 1;
return x;
}
Node* LeftRotation(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = std::max(height(x->left), height(x->right)) + 1;
y->height = std::max(height(y->left), height(y->right)) + 1;
return y;
}
long Balance(Node* N) {
if (N == nullptr)
return 0;
return height(N->left) - height(N->right);
}
Node* Insert(Node* root, int key) {
if (root == nullptr) {
Node* node = new Node;
node->data = key;
node->height = 1;
node->left = nullptr;
node->right = nullptr;
return node;
}
if (key < root->data) {
root->left = Insert(root->left, key);
} else if (key > root->data) {
root->right = Insert(root->right, key);
} else {
return root;
}
root->height = std::max(height(root->left), height(root->right)) + 1;
int balance = Balance(root);
if (balance > 1 && key < root->left->data) {
return RightRotation(root);
}
if (balance < -1 && key > root->right->data) {
return LeftRotation(root);
}
if (balance > 1 && key > root->left->data) {
root->left = LeftRotation(root->left);
return RightRotation(root);
}
if (balance < -1 && key < root->right->data) {
root->right = RightRotation(root->right);
return LeftRotation(root);
}
return root;
}
Node* Delete(Node* root, int key) {
if (root == nullptr) return root;
if ( key < root->data ) {
root->left = Delete(root->left, key);
}else if( key > root->data ) {
root->right = Delete(root->right, key);
} else {
if((root->left == nullptr) || (root->right == nullptr)) {
Node temp = root->left ? root->left : root->right;
if (temp == nullptr)
{
temp = root;
root = nullptr;
}
else {
root = temp;
}
delete temp;
} else {
Node temp = minValueNode(root->right);
root->data = temp->data;
root->right = Delete(root->right, temp->data);
}
}
if (root == nullptr)
return root;
root->height = 1 + std::max(height(root->left), height(root->right));
int balance = Balance(root);
if (balance > 1 &&
Balance(root->left) >= 0)
return RightRotation(root);
if (balance > 1 &&
Balance(root->left) < 0) {
root->left = LeftRotation(root->left);
return RightRotation(root);
}
if (balance < -1 &&
Balance(root->right) <= 0)
return LeftRotation(root);
if (balance < -1 &&
Balance(root->right) > 0) {
root->right = RightRotation(root->right);
return LeftRotation(root);
}
return root;
}
bool Exists(Node root, long key) {
if (root == nullptr)
return false;
if (root->data == key)
return true;
else if (root->data > key)
return Exists(root->left, key);
else
return Exists(root->right, key);
}
Node minValueNode(Node* node) {
Node* current = node;
while (current->left != nullptr)
current = current->left;
return current;
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
char cmd;
AVL tree;
long n;
std::cin >> n;
for (long i = 0; i < n; ++i) {
std::cin >> cmd;
if (cmd == ‘A’) {
long x;
std::cin >> x;
tree.top = tree.Insert(tree.top, x);
std::cout << (tree.top == nullptr? 0 : -tree.Balance(tree.top));
if (i < n - 1) {
std::cout << ‘\n’;
}
} else if (cmd == ‘D’) {
long x;
std::cin >> x;
tree.top = tree.Delete(tree.top, x);
std::cout << (tree.top == nullptr? 0 : -tree.Balance(tree.top));
if (i < n - 1) {
std::cout << ‘\n’;
}
} else if (cmd == ‘C’) {
long x;
std::cin >> x;
tree.Exists(tree.top, x) ? std::cout << ‘Y’ : std::cout << ‘N’;
if (i < n - 1) {
std::cout << ‘\n’;
}
}
}
}
смотри мне нужна такая помощь этот код не проходит 4-й тест(неправильный ответ, тест я не знаю вот задача)
В городе
�
N произошла серия преступлений, расследовать которую пригласили опытного детектива Шерлока Толмса. Он с радостью принялся за новое интересное дело, но не учел, что в этот раз улик оказалось слишком много, и все они имеют совершенно разный “вес” для проведения расследовния.
Шерлок нашел в телефонной книжке номер самого талантливого программиста в городе, которым оказались Вы, и обратился за помощью. Обладая знаниями алгоритмов и структур данных и проанализировав ситуацию, Вы решили хранить все зацепки в виде АВЛ-дерева, чтобы при необходимости достаточно быстро находить любой объект, при этом учитывая вес каждого свидетельства.
Во время расследования дела, Вам предстоит не только добавлять новые улики, но и удалять те, которые уже потеряли актуальность, а также проверять наличие определенных улик. К сожалению, не все знают как работает АВЛ-дерево, поэтому коллеги попросили Вас выводить баланс дерева после каждой операции вставки и удаления.
Входные данные
В первой строке находится число
�
n
(
1
≤
�
≤
2
∗
1
0
5
)
(1≤n≤2∗10
5
) - число операций. Изначально улик нет. В каждой из последующих
�
n строк находится описание одной из трех операций:
�
A
�
x - поместить улику с весом
�
x в дерево. Если она уже было добавлена, операция игнорируется
�
D
�
x - удалить потерявшую актуальность улику, которое имеет вес
�
x. Если такой нет, операция игнорируется.
�
C
�
x - проверить наличие улики с весом
�
x.
Выходные данные
Для каждой операции вида
�
C
�
x выведите
�
Y, если такая улика содержится в дереве, и
�
N, если не содержится.
Для каждой операции вида
�
A
�
x или
�
D
�
x выведите баланс корня дерева после выполнения операции.
Если дерево пустое (в нем нет вершин), выведите
0
0.
Вывод для каждой операции должен содержаться на отдельной строке.
STDIN STDOUT
6
A 3
A 4
A 5
C 4
C 6
D 5
0
1
0
Y
N
-1
Примечание
Операции вставки и удаления требуется реализовать точно так же, как это было сделано в предыдущих задачах, потому что в ином случае баланс корня может отличаться от требуемого.
смотри меня волнует примечание поэтому вот реализации прошлых задач
Задача про баланс:
#include
#include
struct Node {
int data;
int left;
int right;
int height;
};
int CalcHeight(int index, Node arr[]) {
if (index == -1) return 0;
if (arr[index].height > 0) return arr[index].height;
arr[index].height = 1 + std::max(CalcHeight(arr[index].left, arr), CalcHeight(arr[index].right, arr));
return arr[index].height;
}
int CalcBalance(int index, Node arr[]) {
if (index == -1) return 0;
return CalcHeight(arr[index].right, arr) - CalcHeight(arr[index].left, arr);
}
int main() {
int n;
int data;
int left;
int right;
std::cin >> n;
Node arr[n];
for (int i = 0; i < n; ++i) {
std::cin >> data >> left >> right;
arr[i].data = data;
arr[i].left = left - 1;
arr[i].right = right - 1;
arr[i].height = 0;
}
for (int i = 0; i < n; ++i) {
arr[i].height = CalcHeight(i, arr);
}
for (int i = 0; i < n; ++i) {
std::cout << CalcBalance(i, arr) << ‘\n’;
}
}
Задача про Insert:
#include
struct Node {
int data;
int height;
Node* left;
Node* right;
};
struct NedoNode {
int data;
int left;
int right;
};
int height(Node N) {
if (N == nullptr) return 0;
return N->height;
}
Node ReCalculateHeight(Node* root) {
if (root == nullptr) {
return nullptr;
}
root->left = ReCalculateHeight(root->left);
root->right = ReCalculateHeight(root->right);
root->height = 1 + std::max(height(root->left), height(root->right));
return root;
}
Node* BuildTree(NedoNode arr[], int index, int n) {
if (index < 0 || index >= n) {
return nullptr;
}
Node* node = new Node;
node->data = arr[index].data;
node->left = BuildTree(arr, arr[index].left, n);
node->right = BuildTree(arr, arr[index].right, n);
node->height = 1 + std::max(height(node->left), height(node->right));
return node;
}
Node* LeftRotation(Node* x) {
Node y = x->right;
Node T2 = y->left;
y->left = x;
x->right = T2;
x->height = std::max(height(x->left), height(x->right)) + 1;
y->height = std::max(height(y->left), height(y->right)) + 1;
return y;
}
Node RightRotation(Node y) {
Node x = y->left;
Node T2 = x->right;
x->right = y;
y->left = T2;
y->height = std::max(height(y->left), height(y->right)) + 1;
x->height = std::max(height(x->left), height(x->right)) + 1;
return x;
}
int Balance(Node root) {
if (root == nullptr) return 0;
return height(root->left) - height(root->right);
}
Node Insert(Node* root, int key) {
if (root == nullptr) {
Node* node = new Node;
node->data = key;
node->height = 1;
node->left = nullptr;
node->right = nullptr;
return node;
}
if (key < root->data) {
root->left = Insert(root->left, key);
} else if (key > root->data) {
root->right = Insert(root->right, key);
} else {
return root;
}
root->height = std::max(height(root->left), height(root->right)) + 1;
int balance = Balance(root);
if (balance > 1 && key < root->left->data) {
return RightRotation(root);
}
if (balance < -1 && key > root->right->data) {
return LeftRotation(root);
}
if (balance > 1 && key > root->left->data) {
root->left = LeftRotation(root->left);
return RightRotation(root);
}
if (balance < -1 && key < root->right->data) {
root->right = RightRotation(root->right);
return LeftRotation(root);
}
return root;
}
void PrintCurrentLevel(Node* root, int level, int& counter_childs, int& index, NedoNode arr[]) {
if (root == nullptr) return;
if (level == 1) {
arr[index].data = root->data;
if (root->left != nullptr) {
arr[index].left = ++counter_childs;
} else {
arr[index].left = 0;
}
if (root->right != nullptr) {
arr[index].right = ++counter_childs;
} else {
arr[index].right = 0;
}
++index;
}
else if (level > 1) {
PrintCurrentLevel(root->left, level - 1, counter_childs, index, arr);
PrintCurrentLevel(root->right, level - 1, counter_childs, index, arr);
}
}
void PrintLevelOrder(Node* root, NedoNode arr[]) {
int h = height(root);
int counter_childs = 1;
int index = 0;
for (int i = 1; i <= h; i++) {
PrintCurrentLevel(root, i, counter_childs, index, arr);
}
}
int main() {
int n;
int data;
int left;
int right;
std::cin >> n;
NedoNode arr[n + 1];
for (int i = 0; i < n; ++i) {
std::cin >> data >> left >> right;
arr[i].data = data;
arr[i].left = left - 1;
arr[i].right = right - 1;
}
int new_value;
std::cin >> new_value;
Node* root;
root = BuildTree(arr, 0, n);
//root = ReCalculateHeight(root);
root = Insert(root, new_value);
std::cout << n + 1 << ‘\n’;
PrintLevelOrder(root, arr);
for (int i = 0; i < n + 1; ++i) {
std::cout << arr[i].data << ’ ';
std::cout << arr[i].left << ’ ';
std::cout << arr[i].right << ‘\n’;
}
}
задачи про удаление небыло,
смотри я выяснил что ошибка гдето в этих местах: ротации(особенно в удалении) возможно балансировка(мне кажется нужно сделать не left.- right а наоборот как было в задачи про балансировку)