Cod sursa(job #906961)

Utilizator alinaelenaFMI Colceag Alina alinaelena Data 7 martie 2013 14:54:49
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.64 kb
#include <cstdio>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#define nc 30
#define a1 100000009
#define a2 6666013
#define b1 8976578
#define b2 9999678
#define size 1000000
using namespace std;
int const1,const2;
int i;
int poz1(int x)
{
    return (x%(long long)const1) % (long long)size;
}

int poz2(int x)
{
    return (x%(long long)const2) % (long long)size;
}

int find(int x,int *h1,int *h2)
{
    int hash_1 = poz1(x);
    int hash_2 = poz2(x);
	if(h1[hash_1]==x || h2[hash_2]==x)
        return 1;
        return 0;
}

 int add(int x,int *h1,int *h2)
{
    int i,aux;
	int care=1;

    if (find(x,h1,h2) == 1)
    {
        return 1;
    }

    for(i=1;i<=nc;i++)
    {
        int hash_1 = poz1(x);
        int hash_2 = poz2(x);
        if(h1[hash_1]==0)
        {
            h1[hash_1]=x;
            return 1;
        }
        else if(h2[hash_2]==0)
        {
                h2[hash_2]=x;
                return 1;
        }
        else if (care==1)
        {
                aux=h1[hash_1];
                h1[hash_1]=x;
                x=aux;
        }
        else
        {
                aux=h2[hash_2];
                h2[hash_2]=x;
                x=aux;
        }
        care=-care;
    }
	return 0;
}


int erase(int x,int *h1,int *h2)
{
    int hash_1 = poz1(x);
    int hash_2 = poz2(x);

    if(h1[hash_1]==x)
    {
        h1[hash_1]=0;
        return 1;
    }
    if(h2[hash_2]==x)
    {
        h2[hash_2]=0;
        return 1;
    }
    return 0;
}

void rehash()
{
    const1=a1+rand()%b1;
    const2=a2+rand()%b2;
}




int main()
{
    freopen("hashuri.in","r",stdin);
    freopen("hashuri.out","w",stdout);
    int n,op,x;
    scanf("%d",&n);
    srand(time(NULL));

    const1=a1+rand()%b1;
    const2=a2+rand()%b2;

    int *h1=new int[size];
    int *h2=new int[size];
    int ok = 0;
    while (ok == 0)
    {
        ok = 1;
        rehash();
        FILE *in = fopen("hashuri.in","r");
        FILE *out = fopen("hashuri.out","w");
        fscanf(in,"%d",&n);
        fill(h1,h1+size,0);
        fill(h2,h2+size,0);
        while(n!=0)
        {
            fscanf(in,"%d%d",&op,&x);
            if(op==1)
            {
                if(add(x,h1,h2)==0)
                {
                    ok = 0;
                    break;
                }
            }

            if(op==2)
            {
                erase(x,h1,h2);
            }

            if(op==3)
            {
                fprintf(out,"%d\n",find(x,h1,h2));
            }
            n--;
        }
    }

    return 0;

}