Pagini recente » Cod sursa (job #1166437) | Cod sursa (job #1311142) | Cod sursa (job #2758873) | Cod sursa (job #599062) | Cod sursa (job #1345534)
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int key;
int height;
int nrNodes;
Node *st, *dr;
Node() : key(0), height(0), nrNodes(0), st(nullptr), dr(nullptr)
{
}
Node(const int k, const int h, const int n, Node* lt, Node* rt) : key(k), height(h), nrNodes(n), st(lt), dr(rt)
{
}
};
Node *root, *NIL;
void initAVL()
{
NIL = new Node(0, 0, 0, nullptr, nullptr);
root = NIL;
}
void update(Node*& T)
{
T->height = 1 + max(T->st->height, T->dr->height);
T->nrNodes = 1 + T->st->nrNodes + T->dr->nrNodes;
}
void rol(Node*& T)
{
Node *aux = T->st;
T->st = aux->dr;
aux->dr = T;
update(T);
update(aux);
T = aux;
}
void ror(Node*& T)
{
Node *aux = T->dr;
T->dr = aux->st;
aux->st = T;
update(T);
update(aux);
T = aux;
}
void balance(Node*& T)
{
if ( T->st->height > T->dr->height + 1 )
rol(T);
if ( T->dr->height > T->st->height + 1 )
ror(T);
update(T);
}
void insert(Node*& T, const int k)
{
if ( T == NIL )
{
T = new Node(k, 1, 1, NIL, NIL);
}
else
{
if ( k < T->key )
insert(T->st, k);
else
if ( k > T->key )
insert(T->dr, k);
balance(T);
}
}
void erase(Node*& T, const int k)
{
if ( T == NIL ) return;
if ( k < T->key )
erase(T->st, k);
else
if ( k > T->key )
erase(T->dr, k);
else
{
if ( T->st == NIL && T->dr == NIL )
{
delete T;
T = NIL;
return;
}
if ( T->st->height > T->dr->height + 1 )
{
rol(T);
erase(T->dr, k);
}
else
{
ror(T);
erase(T->st, k);
}
}
update(T);
}
bool find(Node*& T, const int k)
{
if ( T == NIL ) return false;
if ( T->key == k ) return true;
if ( k < T->key ) return find(T->st, k);
else return find(T->dr, k);
}
int main()
{
ifstream in("hashuri.in");
ofstream out("hashuri.out");
ios_base::sync_with_stdio( false );
int N;
initAVL();
in >> N;
while ( N-- )
{
int tip, x;
in >> tip >> x;
switch(tip)
{
case 1: insert(root, x); break;
case 2: erase(root, x); break;
case 3: out << find(root, x) << "\n"; break;
default: cerr << "Error\n";
}
}
return 0;
}