Pagini recente » Cod sursa (job #3251448) | Cod sursa (job #2824134) | Cod sursa (job #1679126) | Cod sursa (job #1929588) | Cod sursa (job #904403)
Cod sursa(job #904403)
#include<fstream>
#include<algorithm>
#include<cmath>
#include<ctime>
using namespace std;
ifstream f("hashuri.in");
ofstream g("hashuri.out");
class cockooHash {
int *H1, *H2, size, limit, prime;
int a1, b1, a2, b2;
bool *viz1, *viz2;
void make_hash_function(int &a, int &b) {
a = rand() % size;
b = rand() % size;
}
int hash1(int val) {
return((this->a1 * val + this->b1) % this->prime) % size;
}
int hash2(int val) {
return((this->a2 * val + this->b2) % this->prime) % size;
}
void rehash() {
make_hash_function(this->a1, this->b1);
make_hash_function(this->a2, this->b2);
}
public:
cockooHash(int size) {
this->size = size;
this->limit = (int)log2(size);
this->prime = 1073807359;
this->H1 = new int[size];
this->H2 = new int[size];
fill(this->H1, this->H1+size, 0);
fill(this->H2, this->H2+size, 0);
this->viz1 = new bool[size];
this->viz2 = new bool[size];
fill(this->viz1, this->viz1+size, false);
fill(this->viz2, this->viz2+size, false);
make_hash_function(this->a1, this->b2);
make_hash_function(this->a2, this->b2);
}
bool find(int val) {
int poz1 = this->hash1(val);
int poz2 = this->hash2(val);
if(this->H1[poz1] == val && this->viz1[poz1] == true)
return true;
if(this->H2[poz2] == val && this->viz2[poz2] == true)
return true;
return false;
}
bool erase(int val) {
int poz1 = this->hash1(val);
int poz2 = this->hash2(val);
if(this->H1[poz1] == val && this->viz1[poz1] == true) {
this->viz1[poz1] = false;
return true;
}
if(this->H2[poz2] == val && this->viz2[poz2] == true) {
this->viz2[poz2] = false;
return true;
}
return false;
}
bool insert(int val) {
int i, x, poz1, poz2;
x = val;
poz1 = this->hash1(x);
poz2 = this->hash2(x);
if(this->viz1[poz1] == false) {
this->H1[poz1] = x;
this->viz1[poz1] = true;
return true;
}
for(i=0; i<limit; i+=2) {
if(this->viz2[poz2] == false) {
this->H2[poz2] = x;
this->viz2[poz2] = true;
return true;
}
swap(x, this->H2[poz2]);
poz1 = this->hash1(x);
poz2 = this->hash2(x);
if(this->viz1[poz1] == false) {
this->H1[poz1] = x;
this->viz1[poz1] = true;
return true;
}
swap(x, this->H1[poz1]);
poz1 = this->hash1(x);
poz2 = this->hash2(x);
}
g<<"rehash\n";
return false;
}
};
int main () {
srand(time(0));
int Q, op, val;
cockooHash myHash(900000);
f>>Q;
while(Q--) {
f>>op>>val;
if(op == 1) {
if(!myHash.find(val))
myHash.insert(val);
}
if(op == 2) {
if(myHash.find(val))
myHash.erase(val);
}
if(op == 3) {
if(myHash.find(val) == false)
g<<0<<"\n";
else
g<<1<<"\n";
}
}
f.close();
g.close();
return 0;
}