Cod sursa(job #1206340)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 9 iulie 2014 17:37:46
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <cstdio>
#include <time.h>
#include <cstdlib>
#include <cstring>

#define Hmax 7
#define INF 0x3f3f3f3f

using namespace std;
int H;

int get_lvl()
{
    int lvl = 0,x = rand();
    while(x & 1) ++lvl,x >>= 1;
    if(lvl > H)
        lvl = ++H;
    return lvl;
}

class Skiplist{
public:
    int inf,nivel;
    Skiplist *prev,*next[Hmax];
    Skiplist(int valoare,int nivel){
        this->inf = valoare;
        this->nivel = nivel;
        memset(next,0,sizeof(next));
        prev = 0;
    }
} *root,*path[Hmax];

int cauta(int valoare){
    Skiplist *nodc = root;
    for(int i = H; i < Hmax; ++i) path[i] = nodc;
    for(int i = nodc->nivel; i >= 0; --i)
    {
        for(nodc; nodc->next[i] && nodc->next[i]->inf < valoare; nodc = nodc->next[i]);
        path[i] = nodc;
    }
    if(nodc->next[0] && nodc->next[0]->inf == valoare) return 1;
    return 0;
}

void Insert(int valoare)
{
    if(cauta(valoare)) return;
    Skiplist *aux = new Skiplist(valoare,get_lvl());
    if(path[0]->next[0])
        path[0]->next[0]->prev = aux;
    aux->prev = path[0];
    for(int i = 0;i <= aux->nivel; ++i)
    {
        aux->next[i] = path[i]->next[i];
        path[i]->next[i] = aux;
    }
}

void Delete(int valoare)
{
    if(!cauta(valoare)) return;
    Skiplist *aux = path[0]->next[0];
    if(aux->next[0])
        aux->next[0]->prev = path[0];
    for(int i = 0; i < Hmax; ++i)
        if(path[i]->next[i] == aux)
            path[i]->next[i] = aux->next[i];
    delete aux;
}
int N;

int main()
{
    root = new Skiplist(-2*INF,Hmax - 1);
    for(int i = 0; i < Hmax; ++i) path[i] = root;

    freopen("hashuri.in","r",stdin);
    freopen("hashuri.out","w",stdout);

    scanf("%d",&N);
    int op,x;
    for(int i = 1; i <= N; ++i)
    {
        scanf("%d%d",&op,&x);
        if(op == 1)
            Insert(x);
        else
            if(op == 2)
                Delete(x);
            else
                printf("%d\n",cauta(x));
    }


    return 0;
}