Pagini recente » Cod sursa (job #1786127) | Cod sursa (job #2943701) | Cod sursa (job #2100010) | Cod sursa (job #759889) | Cod sursa (job #920349)
Cod sursa(job #920349)
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<fstream>
#include<time.h>
#define mod 1000003
#define inf 0
using namespace std;
class cuckoo
{
int *H1,*H2,n,r1,r2;
public:
cuckoo(int);
~cuckoo();
int h1(int);
int h2(int);
int Cautare(int);
void Inserare(int,int);
void Stergere(int);
void Hashing();
void Init0();
void ReHashing();
};
cuckoo :: cuckoo(int x)
{
n=x;
H1=new int[n];
H2=new int[n];
srand(time(NULL));
r1=rand()%mod;
r2=rand()%mod;
}
cuckoo :: ~cuckoo()
{
delete[] H1;
delete[] H2;
}
void cuckoo :: Init0()
{
for(int i=0;i<n;i++)
{
H1[i]=H2[i]=inf;
}
}
int cuckoo :: h1(int x)
{
return ((long long)x+(long long)r1)%(long long)n;
}
int cuckoo :: h2(int x)
{
return ((long long)x+(long long)r2)%(long long)n;
}
int cuckoo :: Cautare(int x)
{
if(H1[h1(x)]==x || H2[h2(x)]==x)
return 1; //a fost gasit
return 0;
}
void cuckoo :: ReHashing()
{
delete[] H1;
delete[] H2;
Init0();
srand(time(NULL));
r1=rand()%mod;
r2=rand()%mod;
ifstream f("hashuri.in");
ofstream g("hashuri.out");
int nr,nr_op,a,i;
f>>nr_op;
for(i=1;i<=nr_op;i++)
{
f>>nr>>a;
if(nr==1)
{
if(!Cautare(a))Inserare(a,n);
}
if(nr==2)
{
if(Cautare(a))Stergere(a);
}
if(nr==3)
g<<Cautare(a)<<endl;
}
}
void cuckoo :: Inserare(int x,int max)
{
int aux;
if(Cautare(x)==1) return;
while(max)
{
if(H1[h1(x)]==inf)
{
H1[h1(x)]=x;return;
}
aux=x;x=H1[h1(x)];H1[h1(x)]=aux;
if(H2[h2(x)]==inf)
{
H2[h2(x)]=x;return;
}
aux=x;x=H2[h2(x)];H2[h2(x)]=aux;
max--;
}
ReHashing();
Inserare(x,max);
}
void cuckoo :: Stergere(int x)
{
if(Cautare(x)==0) return;
if(H1[h1(x)]==x) H1[h1(x)]=inf;
if(H2[h2(x)]==x) H2[h2(x)]=inf;
}
void cuckoo ::Hashing()
{
ifstream f("hashuri.in");
ofstream g("hashuri.out");
int i,a,nr,nr_op;
Init0();
f>>nr_op;
for(i=1;i<=nr_op;i++)
{
f>>nr>>a;
if(nr==1)
Inserare(a,n);
if(nr==2)
Stergere(a);
if(nr==3)
g<<Cautare(a)<<endl;
}
f.close();
g.close();
}
int main()
{
cuckoo H(mod);
H.Hashing();
return 0;
}