Pagini recente » Cod sursa (job #3174916) | Cod sursa (job #246995) | Cod sursa (job #807960) | Cod sursa (job #2989750) | Cod sursa (job #929780)
Cod sursa(job #929780)
#include<cstdio>
#include<cstdlib>
#include<fstream>
#include<cstring>
#include<cmath>
#include<ctime>
using namespace std;
template <typename T>
class Cuckoo
{
T *H;
int size,rand1,rand2;
public:
Cuckoo(int );
int f1(T );
int f2(T );
int insert(T );
void remove(T );
int find(T );
void hash(char[] , char[] );
~Cuckoo();
};
template <typename T>
Cuckoo<T>::Cuckoo(int s)
{
size=s;
H=new T[size];
}
template <typename T>
Cuckoo<T>::~Cuckoo()
{
delete[] H;
}
template <typename T>
int Cuckoo<T>::f1(T x)
{
return ((long long)x+(long long)rand1)%(long long)size;
}
template <typename T>
int Cuckoo<T>::f2(T x)
{
return ((long long)x+(long long)rand2)%(long long)size;
}
template <typename T>
void Cuckoo<T>::hash(char i[],char o[])
{
srand(time(NULL));
int n,op,rehash=0;
T x;
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);
}
template <typename T>
int Cuckoo<T>::insert(T x)
{
if(find(x)) return 1;
int pos1,pos2,c=0,last=2;
T aux;
while(c<=log2(size))
{
pos1=f1(x);pos2=f2(x);
if(H[pos1]==0)
{
H[pos1]=x;
return 1;
}
else if(H[pos2]==0)
{
H[pos2]=x;
return 1;
}
else
{
if(last==2)
{
aux=H[pos1];
H[pos1]=x;
x=aux;
last=1;
}
else
{
aux=H[pos2];
H[pos2]=x;
x=aux;
last=2;
}
}
c++;
}
return 0;
}
template <typename T>
void Cuckoo<T>::remove(T x)
{
int pos;
pos=f1(x);if(H[pos]==x) H[pos]=0;
pos=f2(x);if(H[pos]==x) H[pos]=0;
}
template <typename T>
int Cuckoo<T>::find(T x)
{
if(H[f1(x)]==x || H[f2(x)]==x) return 1;
return 0;
}
int main()
{
Cuckoo<int> HTab(1000003);
HTab.hash("hashuri.in","hashuri.out");
return 0;
}