Pagini recente » Cod sursa (job #1929835) | Statistici Obreja Ionela Loredana (obrejaionela) | Cod sursa (job #3270615) | Cod sursa (job #2352807) | Cod sursa (job #908234)
Cod sursa(job #908234)
#include <math.h>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <time.h>
using namespace std;
class cuckoo_set
{
int *h1,*h2;
int hash_size;
int a,b,c,d;
long long prim;
public:
cuckoo_set(int size,int p=1000000009)
{
h1 = new int[size];
h2 = new int[size];
hash_size = size;
fill(h1,h1+size,0);
fill(h2,h2+size,0);
prim=p;
}
~cuckoo_set()
{
delete [] h1;
delete [] h2;
a=b=c=d=hash_size=0;
prim=0;
}
bool insert(int value)
{
int cycles=0,aux=value,sw=1;
bool found=false;
if (find(value)) return true;
while (!found)
{
int poz1 = function1(value);
int poz2 = function2(value);
cycles++;
if (h1[poz1] == 0)
{
h1[poz1] = value;
found = true;
}
else if(h2[poz2] == 0)
{
h2[poz2] = value;
found = true;
}
else
{
if (sw==1)
{
aux = value;
value = h1[poz1];
h1[poz1] = aux;
}
else
{
aux = value;
value = h2[poz2];
h2[poz2] = aux;
}
sw*=-1;
}
if ((cycles > log2(this->hash_size))&&(!found)){return false;} //numarul de incercari nu depaseste log size
}
return true;
}
void erase(int value)
{
int poz1 = function1(value);
int poz2 = function2(value);
if (h1[poz1] == value)
{
h1[poz1] = 0;
}
else if (h2[poz2] == value)
{
h2[poz2] = 0;
}
}
int find(int value)
{
int poz1 = function1(value);
int poz2 = function2(value);
if (h1[poz1] == value || h2[poz2] == value)
{
return 1;
}
else
{
return 0;
}
}
int function1(int value)
{
return (((long long)a+(long long)value * (long long)b ) % (long long)prim )% (long long)hash_size;
}
int function2(int value)
{
return (((long long)b+(long long)value * (long long)a ) % (long long)prim ) %(long long)hash_size;
}
void make_hash_function()
{
a = rand() % hash_size;
b = rand() % hash_size;
}
int rehash(string a, string b)
{
bool ok = false;
ifstream in(a.c_str());
ofstream out(b.c_str());
while (ok == false)
{
in.clear();
int N;
bool ok2=true;
make_hash_function();
in >> N;
for (int i =0;i<N;i++)
{
int x , op;
in >> op >> x;
switch (op)
{
case 1:
if ( !insert(x) )
{
ok = false;
break;
}
case 2:
erase(x);
break;
case 3:
out << find(x) << "\n";
break;
}
}
ok = true;
}
return 0;
}
};
int main()
{ cuckoo_set t(1000001);
t.rehash("hashuri.in","hashuri.out");
return 0;
}