Pagini recente » Cod sursa (job #2963715) | Cod sursa (job #2962195) | Cod sursa (job #3003216) | Cod sursa (job #2690615) | Cod sursa (job #911338)
Cod sursa(job #911338)
#include<cstdio>
#include<cstdlib>
#include<fstream>
#include<cstring>
#include<cmath>
#include<ctime>
using namespace std;
class Cuckoo
{
int *H,size,rand1,rand2;
public:
Cuckoo(int );
int f1(int );
int f2(int );
int insert(int );
void remove(int );
int find(int );
void hash(char[] , char[] );
};
Cuckoo::Cuckoo(int s)
{
size=s;
H=new int[size];
}
int Cuckoo::f1(int x)
{
return ((long long)x*(long long)rand1)%(long long)size;
}
int Cuckoo::f2(int x)
{
return ((long long)x*(long long)rand2)%(long long)size;
}
void Cuckoo::hash(char i[],char o[])
{
srand(time(NULL));
int n,op,x,rehash=0;
do{
ifstream in(i);
ofstream out(o);
fill(H,H+size,0);
rand1=rand()%size;
rand2=rand()%size;
in>>n;
for(int i=0;i<n;i++)
{
in>>op>>x;
if(op==1)
rehash=!insert(x);
if(op==2) remove(x);
if(op==3) out<<find(x)<<"\n";
}
in.close();
out.close();
}while(rehash==1);
}
int Cuckoo::insert(int x)
{
if(find(x)) return 1;
int pos1,pos2,c=0,last=2,aux;
while(c<=log2(size))
{
if(last==2)
{
pos1=f1(x);
if(H[pos1]==0)
{
H[pos1]=x;
return 1;
}
else
{
aux=H[pos1];
H[pos1]=x;
x=aux;
last=1;
}
}
else
{
pos2=f2(x);
if(H[pos2]==0)
{
H[pos2]=x;
return 1;
}
else
{
aux=H[pos2];
H[pos2]=x;
x=aux;
last=2;
}
}
c++;
}
return 0;
}
void Cuckoo::remove(int x)
{
int pos;
pos=f1(x);if(H[pos]==x) H[pos]=0;
pos=f2(x);if(H[pos]==x) H[pos]=0;
}
int Cuckoo::find(int x)
{
if(H[f1(x)]==x || H[f2(x)]==x) return 1;
return 0;
}
int main()
{
Cuckoo HTab(1000003);
HTab.hash("hashuri.in","hashuri.out");
return 0;
}