Pagini recente » Cod sursa (job #2462731) | Cod sursa (job #891953) | Cod sursa (job #1876535) | Cod sursa (job #889685) | Cod sursa (job #947792)
Cod sursa(job #947792)
#include<stdio.h>
#include<cstdlib>
#include<ctime>
FILE*f=fopen("hashuri.in","r");
FILE*g=fopen("hashuri.out","w");
struct treap{
int priority,key;
treap *ls,*rs;
treap ( int priority , int key , treap *ls , treap *rs ){
this->priority = priority;
this->key = key;
this->ls = ls;
this->rs = rs;
}
}*R,*nul;
inline void rotate_left ( treap *&nod ){
treap *fiu = nod->ls;
nod->ls = fiu->rs;
fiu->rs = nod;
nod = fiu;
}
inline void rotate_right ( treap *&nod ){
treap *fiu = nod->rs;
nod->rs = fiu->ls;
fiu->ls = nod;
nod = fiu;
}
inline void balance ( treap *&nod ){
if ( nod->ls->priority > nod->priority ){
rotate_left(nod);
}
else{
if ( nod->rs->priority > nod->priority ){
rotate_right(nod);
}
}
}
void insert ( treap *&nod , const int &key ){
if ( nod == nul ){
nod = new treap(rand()+1,key,nul,nul);
return ;
}
if ( nod->key > key ){
insert(nod->ls,key);
}
else{
if ( nod->key < key ){
insert(nod->rs,key);
}
}
balance(nod);
}
void erase ( treap *&nod , const int &key ){
if ( nod == nul ) return ;
if ( nod->key > key ){
erase(nod->ls,key);
}
else{
if ( nod->key < key ){
erase(nod->rs,key);
}
else{
if ( nod->ls == nul && nod->rs == nul ){
delete nod; nod = nul;
return ;
}
if ( nod->ls->priority >= nod->rs->priority ){
rotate_left(nod);
}
else{
rotate_right(nod);
}
erase(nod,key);
}
}
}
bool search ( treap *&nod , const int &key ){
if ( nod == nul ) return 0;
if ( nod->key == key ) return 1;
if ( nod->key > key ) return search(nod->ls,key);
else return search(nod->rs,key);
}
int main () {
R = nul = new treap(0,0,NULL,NULL);
srand(time(NULL));
int op;
fscanf(f,"%d",&op);
int tip,x;
while ( op-- ){
fscanf(f,"%d %d",&tip,&x);
if ( tip == 1 ){
insert(R,x);
}
else{
if ( tip == 2 ){
erase(R,x);
}
else{
fprintf(g,"%d\n",search(R,x));
}
}
}
fclose(f);
fclose(g);
return 0;
}