Cod sursa(job #306506)

Utilizator utcistuBarcau Tomsa utcistu Data 21 aprilie 2009 01:04:35
Problema Hashuri Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 2.3 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define nMax 1000001
#include <time.h>
#define H 21

typedef struct node
{
    int val,h;
    struct node **link;
}SLT;

SLT head,collect;

SLT *SLfind(int x)
{
    int deg=H-1;
    SLT *p=&head;
    memset(collect.link,'\0',H*sizeof(SLT*));
    while (deg>=0)
    {
        while (p->link[deg]!=NULL)
        {
            if (p->link[deg]->val<x) p=p->link[deg];
            else break;
        }
        collect.link[deg--]=p;
    }
    return p;
}

void SLdelete(int x)
{
    SLT *p=SLfind(x)->link[0];
    int deg=0;
    if (p)
    {
        if (p->val==x)
        {
            for (;deg<p->h;deg++)
            {
                collect.link[deg]->link[deg]=p->link[deg];
            }
            free(p);
        }
    }
}

void SLinsert(int x)
{
    SLT *p=SLfind(x),*q;
    int deg=0,h,r;
    if (p->link[0])
    {
        if (p->link[0]->val==x)
        {
            return;
        }
    }
    for (h = 1, r = rand(); r % 2; r >>= 1, h++);
    if (h > H) h = H ;
    q=(SLT *)malloc(sizeof(SLT));
    q->link=(SLT **)malloc(h*sizeof(SLT*));q->val=x;q->h=h;
    for (;deg<h;deg++)
    {
        q->link[deg]=collect.link[deg]->link[deg];
        collect.link[deg]->link[deg]=q;
    }
}

int main()
{
    srand((unsigned int)time(0));
    int i,n,cmd,x;
    SLT *q;
    FILE *fin,*fout;
    fin=fopen("hashuri.in","r");
    fout=fopen("hashuri.out","w");
    head.link=(SLT **)malloc(H*sizeof(SLT*));head.val=-1;head.h=H;
    collect.link=(SLT **)malloc(H*sizeof(SLT*));collect.val=-1;collect.h=H;
    memset(head.link,'\0',H*sizeof(SLT*));
    fscanf(fin,"%d",&n);
    for (i=0;i<n;i++)
    {
        fscanf(fin,"%d %d",&cmd,&x);
        switch (cmd)
        {
            case 1:SLinsert(x);
            break;
            case 2:SLdelete(x);
            break;
            case 3:
            q=SLfind(x);
            if (q->link[0]!=NULL)
            {
                if (q->link[0]->val==x)
                    {
                        fputs("1\n",fout);
                        break;
                    }
            }
            fputs("0\n",fout);
            break;
            default:
            break;
        }
    }
    fclose(fout);
    return 0;
}