Cod sursa(job #1101449)

Utilizator ctlin04UAIC.VlasCatalin ctlin04 Data 8 februarie 2014 14:57:31
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.63 kb
//Treap- operatii de baza
#include<fstream>
#include<stdlib.h>
using namespace std;
typedef struct treap {
            int key,weight;
            treap *l, *r;
            treap () { l=0; r=0; }
            };
treap *root;
int op, n, k, w;       
 
treap *rotright(treap *nod) {
    treap *aux=nod->l;
    nod->l=aux->r;
    aux->r=nod;
     
    return(aux);
}
 
treap *rotleft(treap *nod) {
    treap *aux=nod->r;
    nod->r=aux->l;
    aux->l=nod;
     
    return(aux);
}    
 
treap *balance(treap *nod) {
    
    if (nod->l==0&&nod->r!=0&&nod->r->weight>nod->weight) nod=rotleft(nod);
     else if (nod->r==0&&nod->l!=0&&nod->l->weight>nod->weight) nod=rotright(nod);
      else if (nod->r!=0&&nod->l!=0) {
              if ( nod->r->weight>nod->weight && nod->r->weight>=nod->l->weight) nod=rotleft(nod);
               else if (nod->l->weight>nod->weight&& nod->l->weight>nod->r->weight) nod=rotright(nod);
               }
                   
    return(nod);
     
}
 
treap *insert(treap *nod, treap *newnod) {
    if (nod==0) return(newnod);
     
    if (newnod->key<nod->key) nod->l=insert(nod->l, newnod);
     else if (newnod->key>nod->key) nod->r=insert(nod->r, newnod);
      else return( nod );
     
    return( balance(nod) );
}

void erase(treap* &n, int key) {
    if (n==0) return;
    
    if (key < n->key)
        erase(n->l, key);
    else if (key > n->key)
        erase(n->r, key);
    else {    
        if (n->l == 0 && n->r == 0) n = 0;
        else {
             if (n->l==0) n=rotleft(n);
              else if (n->r==0) n=rotright(n);
              else (n->l->weight <= n->r->weight) ? n=rotleft(n) : n=rotright(n);
            erase(n, key);
        }
    }
}
 
int cauta(treap *nod, int v) {
    if (nod==0) return(0);
     else if (nod->key>v) return(cauta(nod->l,v));
      else if (nod->key<v) return(cauta(nod->r,v));
       else return(1);
}
 
int main(void) {
   ifstream cin("hashuri.in");
   ofstream cout("hashuri.out");
    srand(time(NULL));
    
    cin>>n;
    for (; n>0; --n) {
        cin>>op;
        if (op==1) {
                   cin>>k;
                   w=rand() % 1000000007+1;
                   treap *aux=new treap;
                   aux->key=k;
                   aux->weight=w;
                   if (root==0) root=aux;
                    else root=insert(root, aux);
                   }
        else if (op==2){
               cin>>k;
               erase(root,k);
               }
        else { 
             cin>>k;
              cout<<cauta(root,k)<<"\n";
              }
        }
   // getch();
  return(0);
}