Cod sursa(job #905846)

Utilizator maritimCristian Lambru maritim Data 6 martie 2013 11:23:35
Problema Hashuri Scor 60
Compilator c Status done
Runda Arhiva educationala Marime 1.83 kb
#include<stdio.h>

#define M 2077771
#define H1 700127
#define H2 501131

inline int h1(int a,int hf1,int hf2)
{
    return (1LL*hf1*a+hf2)%M;
}

inline int h2(int a,int hf1,int hf2)
{
    return (1LL*hf2*a+hf1)%M;
}

inline void initializare(int *p)
{
    int i;

    for(i=0;i<M;i++)
        *(p+i) = 0;
}

inline int exist(int *p,int x,int hf1,int hf2)
{
    if(*(p+h1(x,hf1,hf2)) == x || *(p+h2(x,hf1,hf2)) == x)
        return 1;
    return 0;
}

inline void reordonate(int *p,int x,int hf1,int hf2)
{
    int hash2 = h2(x,hf1,hf2),y;

    if(*(p+hash2) != 0)
    {
        y = *(p+hash2);
        *(p+hash2) = x;
        reordonate(p,y,hf1,hf2);
    }
    else
        *(p+hash2) = x;
}

inline void add(int *p,int x,int hf1,int hf2)
{
    if(exist(p,x,hf1,hf2))
        return ;

    int hash1 = h1(x,hf1,hf2),y;

    if(*(p+hash1) != 0)
    {
        y = *(p+hash1);
        *(p+hash1) = x;
        reordonate(p,y,hf1,hf2);
    }
    else
        *(p+hash1) = x;
}

inline void sterge(int *p,int x,int hf1,int hf2)
{
    int hash1 = h1(x,hf1,hf2),hash2 = h2(x,hf1,hf2);

    if(*(p+hash1) == x)
        *(p+hash1) = 0;
    else if(*(p+hash2) == x)
        *(p+hash2) = 0;
}

void main()
{
    FILE *f = fopen("hashuri.in","r");
    FILE *g = fopen("hashuri.out","w");
    int *p;
    int N,op,a;
    int hf1 = H1,hf2 = H2; 
    
    /*hf1 = hash function 1, hf2 = hash function 2*/

    p = (int*)malloc(M*sizeof(int));

    initializare(p);

    int i;

    fscanf(f,"%d",&N);
    for(i=1;i<=N;i++)
    {
        fscanf(f,"%d %d",&op,&a);
        switch(op)
        {
            case 1 : add(p,a,hf1,hf2);
                break;
            case 2 : sterge(p,a,hf1,hf2);
                break;
            case 3 : fprintf(g,"%d\n",exist(p,a,hf1,hf2));
        }
    }

    fclose(f);
    fclose(g);

//    for(i=0;i<M;i++)
//        printf("%d\n",*(p+i));
}