Pagini recente » Cod sursa (job #2972530) | Cod sursa (job #3180304) | Cod sursa (job #2691704) | Cod sursa (job #1646796) | Cod sursa (job #906655)
Cod sursa(job #906655)
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <time.h>
using namespace std;
class Hash_Set
{
int modulo;
int *hash1;
int *hash2;
int hash_size;
int va1;
int vb1;
int va2;
int vb2;
int prim;
public:
Hash_Set(int size)
{
hash1 = new int[size];
hash2 = new int[size];
hash_size = size;
prim = 1000000009;
fill(hash1,hash1+size,0);
fill(hash2,hash1+size,0);
}
bool insert(int&);
void erase(int&);
bool find(int&);
int hash_function1(int&);
int hash_function2(int&);
void make_hash_function();
};
bool DO_HASH()
{
bool ok = false;
srand(time(0));
int mod;
while (ok == false)
{
ifstream input("hashuri.in");
ofstream output("hashuri.out");
Hash_Set t(1000000);
int n;
t.make_hash_function();
input >> n;
for (int i =0;i<n;i++)
{
int x , op;
input >> op >> x;
if (op == 1)
{
if ( !t.insert(x) )
{
ok = false;
break;
}
}
if (op == 2)
{
t.erase(x);
}
if (op == 3)
{
output << t.find(x) << "\n";
}
}
ok = true;
}
}
int main()
{
DO_HASH();
return 0;
}
void Hash_Set::make_hash_function()
{
va1 = rand() % hash_size;
vb1 = rand() % hash_size;
va2 = rand() % hash_size;
vb2 = rand() % hash_size;
}
int Hash_Set::hash_function1(int &value)
{
return (( (long long)va1 + (long long)value * (long long)vb1 ) % (long long)prim) % (long long)hash_size;
}
int Hash_Set::hash_function2(int &value)
{
return (((long long)va2 + (long long)value * (long long)vb2) % (long long)prim) % (long long)hash_size;
}
void Hash_Set::erase(int &value)
{
int h1 = hash_function1(value);
int h2 = hash_function2(value);
if (hash1[h1] == value)
{
hash1[h1] = 0;
}
else if (hash2[h2] == value)
{
hash2[h2] = 0;
}
}
bool Hash_Set::find(int &value)
{
int h1 = hash_function1(value);
int h2 = hash_function2(value);
if (hash1[h1] == value || hash2[h2] == value)
{
return true;
}
else
{
return false;
}
}
bool Hash_Set::insert(int &value)
{
if (find(value)) return true;
int init = value;
char which = 1;
int iteratii = 0;
while (value != 0)
{
iteratii++;
int h1 = hash_function1(value);
int h2 = hash_function2(value);
if (hash1[h1] == 0)
{
hash1[h1] = value;
value = 0;
}
else if(hash2[h2] == 0)
{
hash2[h2] = value;
value = 0;
}
else
{
if (which == 1)
{
int aux = value;
value = hash1[h1];
hash1[h1] = aux;
}
else
{
int aux = value;
value = hash2[h2];
hash2[h2] = aux;
}
which = - which;
}
if (iteratii > 30)
{
return false;
}
}
return true;
}