Pagini recente » Cod sursa (job #2329512) | Cod sursa (job #1885206) | Cod sursa (job #2972238) | Cod sursa (job #2296235) | Cod sursa (job #914145)
Cod sursa(job #914145)
#include<fstream>
#include<algorithm>
#include<cmath>
#include<ctime>
using namespace std;
#define ll long long
class cockooHash
{
int *h1, *h2, table_size, prime_nr, max_steps;
int a1, a2, b1, b2;
bool *viz1, *viz2;
void generate()
{
a1 = rand() % this->table_size;
b1 = rand() % this->table_size;
a2 = rand() % this->table_size;
b2 = rand() % this->table_size;
}
int hash1(int val)
{
return ( ( ( (ll)this->a1 * (ll)val + (ll)this->b1) % (ll)this->prime_nr ) % (ll)this->table_size );
}
int hash2(int val)
{
return ( ( ( (ll)this->a2 * (ll)val + (ll)this->b2) % (ll)this->prime_nr ) % (ll)this->table_size );
}
public:
cockooHash(int dim)
{
this->table_size = dim;
this->prime_nr = 1000000009;
this->max_steps = (int)log2(this->table_size);
this->h1 = new int[this->table_size];
this->h2 = new int[this->table_size];
fill(this->h1, this->h1+this->table_size, 0);
fill(this->h2, this->h2+this->table_size, 0);
this->viz1 = new bool[this->table_size];
this->viz2 = new bool[this->table_size];
fill(this->viz1, this->viz1+this->table_size, false);
fill(this->viz2, this->viz2+this->table_size, false);
generate();
}
bool find(int val)
{
int k1, k2;
k1 = hash1(val);
k2 = hash2(val);
if(this->h1[k1] == val && this->viz1[k1] == true)
return true;
if(this->h2[k2] == val && this->viz2[k2] == true)
return true;
return false;
}
bool erase(int val)
{
int k1 = hash1(val);
int k2 = hash2(val);
if(this->h1[k1] == val && this->viz1[k1] == true)
{
this->h1[k1] = 0;
this->viz1[k1] = false;
return true;
}
if(this->h2[k2] == val && this->viz2[k2] == true)
{
this->h2[k2] = 0;
this->viz2[k2] = false;
return true;
}
return false;
}
bool insert(int val)
{
int x = val;
int k1 = hash1(x);
int k2 = hash2(x);
if(this->h1[k1] == 0 && this->viz1[k1] == false)
{
this->h1[k1] = x;
this->viz1[k1] = true;
return true;
}
for(int i = 0; i<this->max_steps; i+=2)
{
if(this->h2[k2] == 0 && this->viz2[k2] == false)
{
this->h2[k2] = x;
this->viz2[k2] = true;
return true;
}
swap(x, this->h2[k2]);
k1 = hash1(x);
k2 = hash2(x);
if(this->h1[k1] == 0 && this->viz1[k1] == false)
{
this->h1[k1] = x;
this->viz1[k1] = true;
return true;
}
swap(x, this->h1[k1]);
k1 = hash1(x);
k2 = hash2(x);
}
return false;
}
void do_hash()
{
bool ok = false;
while (ok == false)
{
ok = true;
ifstream f("hashuri.in");
ofstream g("hashuri.out");
this->generate();
int n,op,x;
f>>n;
for (int i=1;i<=n;i++)
{
f>>op>>x;
if (op == 1)
{
if (this->insert(x) == false)
{
ok = false;
}
}
else if (op == 2) this->erase(x);
else g<<this->find(x)<<"\n";
}
f.close();
g.close();
}
}
};
int main()
{
cockooHash *hash;
hash=new cockooHash(1000000);
hash->do_hash();
delete hash;
hash = 0;
return 0;
}