Pagini recente » Cod sursa (job #567489) | Cod sursa (job #933453) | Cod sursa (job #212170) | Cod sursa (job #2136600) | Cod sursa (job #916816)
Cod sursa(job #916816)
#include<cstdio>
#include<cstdlib>
#include<fstream>
#include<cstring>
#include<cmath>
#include<ctime>
using namespace std;
class Cuckoo
{
int *H1,*H2,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;
H1=new int[size];
H2=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(H1,H1+size,0);
fill(H2,H2+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))
{
pos1=f1(x);pos2=f2(x);
if(H1[pos1]==0)
{
H1[pos1]=x;
return 1;
}
else if(H2[pos2]==0)
{
H2[pos2]=x;
return 1;
}
else
{
if(last==2)
{
aux=H1[pos1];
H1[pos1]=x;
x=aux;
last=1;
}
else
{
aux=H2[pos2];
H2[pos2]=x;
x=aux;
last=2;
}
}
/* if(last==2)
{
pos=f1(x);
if(H[pos]==0)
{
H[pos]=x;
return 1;
}
else
{
aux=H[pos];
H[pos]=x;
x=aux;
last=1;
}
}
else
{
pos=f2(x);
if(H[pos]==0)
{
H[pos]=x;
return 1;
}
else
{
aux=H[pos];
H[pos]=x;
x=aux;
last=2;
}
}
*/
c++;
}
return 0;
}
void Cuckoo::remove(int x)
{
int pos;
pos=f1(x);if(H1[pos]==x) H1[pos]=0;
pos=f2(x);if(H2[pos]==x) H2[pos]=0;
}
int Cuckoo::find(int x)
{
if(H1[f1(x)]==x || H2[f2(x)]==x) return 1;
return 0;
}
int main()
{
Cuckoo HTab(1000003);
HTab.hash("hashuri.in","hashuri.out");
return 0;
}