Pagini recente » Cod sursa (job #1918122) | Cod sursa (job #46073) | Cod sursa (job #37646) | Cod sursa (job #2582032) | Cod sursa (job #914797)
Cod sursa(job #914797)
#include <cstdio>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
class hash{
int *h1;
int *h2;
int size;
int nc;
int const1,const2;
int a1,b1;
int a2,b2;
public:
hash(int);
~hash();
void setnull();
int add(int x);
int poz1(int x);
int poz2(int x);
int erase(int x);
int find(int x);
void rehash();
void menu();
};
hash::~hash()
{
delete[] h1;
delete[] h2;
}
void hash::menu ()
{
int n,op,x;
srand(time(NULL));
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);
setnull();
while(n!=0)
{
fscanf(in,"%d%d",&op,&x);
if(op==1)
{
if(add(x)==0)
{
ok = 0;
break;
}
}
if(op==2)
{
erase(x);
}
if(op==3)
{
fprintf(out,"%d\n",find(x));
}
n--;
}
fclose(in);
fclose(out);
}
}
hash::hash(int x)
{
h1=new int[x];
h2=new int[x];
h1[3] = 4;
nc=30;
a1= 100000009;
a2= 6666013;
b1= 8976578;
b2= 9999678;
size=x;
}
void hash::rehash()
{
const1=a1+rand()%b1;
const2=a2+rand()%b2;
}
void hash::setnull()
{
int i;
for(i=0;i<size;++i)
h1[i] = h2[i] = 0;
}
int hash::add(int x)
{
int i,aux;
int care=1;
if (find(x)==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 hash::poz1(int x)
{
return (x%(long long)const1) % (long long)size;
}
int hash::poz2(int x)
{
return (x%(long long)const2) % (long long)size;
}
int hash::find(int x)
{
int hash_1 = poz1(x);
int hash_2 = poz2(x);
if(h1[hash_1]==x || h2[hash_2]==x)
return 1;
return 0;
}
int hash::erase(int x)
{
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;
}
int main()
{
// freopen("hashuri.in","r",stdin);
// freopen("hashuri.out","w",stdout);
hash *c;
c = new hash(1000000);
c->menu();
return 0;
}