Pagini recente » Cod sursa (job #1350557) | Cod sursa (job #71053) | Cod sursa (job #2606979) | Cod sursa (job #1033546) | Cod sursa (job #903598)
Cod sursa(job #903598)
//Cuckoo Hashing
#include <stdio.h>
#include <stdlib.h>
int func_hash1(int value, int modulo)
{
return value % modulo;
}
int func_hash2(int value , int modulo)
{
return (int)(value/modulo) % modulo;
}
int find(int value , int modulo , int *hash1 , int *hash2)
{
int h1 = func_hash1(value,modulo);
int h2 = func_hash2(value,modulo);
if (hash1[h1] == value || hash2[h2] == value)
{
return 1;
}
else
{
return 0;
}
}
void erase(int value , int modulo , int *hash1 , int *hash2)
{
int h1 = func_hash1(value,modulo);
int h2 = func_hash2(value,modulo);
if (hash1[h1] == value)
{
hash1[h1] = 0;
}
else if (hash2[h2] == value)
{
hash2[h2] = 0;
}
}
void insert(int value , int modulo , int *hash1 , int *hash2)
{
int init = value;
char which = 1;
while (value != 0)
{
int h1 = func_hash1(value,modulo);
int h2 = func_hash2(value,modulo);
if (hash1[h1] == 0)
{
hash1[h1] = value;
value = 0;
}
else if(hash2[h2] == 0)
{
hash2[h2] = value;
value = 0;
}
else
{
if (which == 1)
{
int aux = value;
value = hash1[h1];
hash1[h1] = aux;
}
else
{
int aux = value;
value = hash2[h2];
hash2[h2] = aux;
}
which = - which;
}
if (init == value && which == 1) break;
}
}
void fill(int *vect , int size)
{
int i;
for (i =0;i<size;i++)
{
vect[i] = 0;
}
}
int main()
{
FILE *input = fopen("hashuri.in","r");
FILE *output = fopen("hashuri.out","w");
int modulo = 666013;
int *hash1 = (int*)malloc(modulo * sizeof(int));
int *hash2 = (int*)malloc(modulo * sizeof(int));
fill(hash1,modulo);
fill(hash2,modulo);
int i,n;
fscanf(input,"%d",&n);
for (i=0;i<n;i++)
{
int x , op;
fscanf(input,"%d%d",&op,&x);
if (op == 1)
{
insert(x,modulo,hash1,hash2);
}
if (op == 2)
{
erase(x,modulo,hash1,hash2);
}
if (op == 3)
{
fprintf(output,"%d\n",find(x,modulo,hash1,hash2));
}
}
return 0;
}