Pagini recente » Clasament iconcurs13 | Cod sursa (job #3275373) | Cod sursa (job #2631803) | Cod sursa (job #3136881) | Cod sursa (job #921530)
Cod sursa(job #921530)
#include <math.h>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <time.h>
#include <math.h>
using namespace std;
template <typename type>
class cuckoo_set
{
type *h1,*h2;
int hash_size;
int a,b;
long long prim;
public:
cuckoo_set(int size,int p=1000000009)
{
h1 = new type[size];
h2 = new type[size];
hash_size = size;
fill(h1,h1+size,0);
fill(h2,h2+size,0);
prim=p;
}
~cuckoo_set()
{
delete [] h1;
delete [] h2;
a=b=hash_size=0;
prim=0;
}
bool insert(type value)
{
int cycles=0,sw=1;
type aux=value;
bool found=false;
if (find(value)) return true;
while (!found)
{
int poz1 = function(value,a,b);
int poz2 = function(value,b,a);
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(type value)
{
int poz1 = function(value,a,b);
int poz2 = function(value,b,a);
if (h1[poz1] == value)
{
h1[poz1] = 0;
}
else if (h2[poz2] == value)
{
h2[poz2] = 0;
}
}
int find(type value)
{
int poz1 = function(value,a,b);
int poz2 = function(value,b,a);
if (h1[poz1] == value || h2[poz2] == value)
{
return 1;
}
else
{
return 0;
}
}
//define function for each type
int function(int value,int a,int b)
{
return (((long long)a+(long long)value * (long long)b ) % (long long)prim )% (long long)hash_size;
}
int function(float value,int a,int b)
{
int exp;
float signif=frexp(value,&exp);
return (((long long)exp+(long long)signif * (long long)b ) % (long long)prim )% (long long)hash_size;
}
int function(double value,int a,int b)
{
int exp;
double signif=frexp(value,&exp);
return (((long long)exp+(long long)signif * (long long)b ) % (long long)prim )% (long long)hash_size;
}
int function(char value,int a,int b)
{
return (((long long)a+(long long)value * (long long)b ) % (long long)prim )% (long long)hash_size;
}
void make_hash_function()
{
a = rand() % hash_size;
b = rand() % hash_size;
}
int hash_from_data(string a, string b)
{
bool ok = false;
ifstream in(a.c_str());
ofstream out(b.c_str());
while (ok == false)
{
in.clear();
int N;
make_hash_function();
in >> N;
for (int i =0;i<N;i++)
{
type x ;int op;
in >> op >> x;
if (op==1)
if ( !insert(x) )
{
ok = false;
break;
}
if (op==2)
erase(x);
if (op==3)
out << find(x) << "\n";
}
ok = true;
}
return 0;
}
};
int main()
{ cuckoo_set <int> t(1000001);
t.hash_from_data("hashuri.in","hashuri.out");
return 0;
}