Pagini recente » Cod sursa (job #788741) | Cod sursa (job #934277) | Cod sursa (job #1542222) | Cod sursa (job #2185383) | Cod sursa (job #917219)
Cod sursa(job #917219)
// Constantin Maria - grupa 134
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;
class Hash
{
int MOD;
int a,b,c;
unsigned int *h1, *h2;
int size_h;
public:
void SetHash();
int Insereaza(unsigned int x);
void Del(unsigned int x);
int Cauta(unsigned int x);
void Citeste();
Hash(unsigned int);
};
Hash::Hash(unsigned int s)
{
size_h = s;
h1 = (unsigned int *) malloc (size_h* sizeof(unsigned int));
h2 = (unsigned int *) malloc (size_h* sizeof(unsigned int));
}
void Hash::SetHash()
{
int mo[]={999983,999979,899981,900007,800011};
a = rand () % 10000000 + 1;
b = rand () % 20008900 + 1;
c = rand () % 10080000 + 1;
MOD = mo[rand () % 5];
}
int Hash::Insereaza (unsigned int x)
{
int ok = 0, st = 1, v1, v2;
unsigned int aux;
v1 = (a * x + b) % MOD;
v2 = (b * x + c*c) % MOD;
while( ok > -30 )
{
if( st == 1 )
{
if(!h1 [v1] || h1 [v1] == x)
{
h1 [v1] = x;
return 1;
}
else
{
st = -1;
if( ok < 0)
{
aux = x;
x = h1 [v1];
h1 [v1] = aux;
v1 = (a * x + b) % MOD;
v2 = (b * x + c*c) % MOD;
}
}
}
if( st == -1)
{
if(!h2 [v2] || h2 [v2] == x)
{
h2 [v2] = x;
return 1;
}
else
{
st = 1;
if( ok < 0)
{
aux = h2[v2];
h2[v2] = x;
x = aux;
v1 = (a * x + b) % MOD;
v2 = (b * x + c*c) % MOD;
}
}
}
ok--;
}
return 0;
}
void Hash::Del(unsigned int x)
{
int v1,v2;
v1 = (a * x + b) % MOD;
v2 = (b * x + c*c) % MOD;
if(h1[v1] == x) h1[v1] = 0;
else if(h2[v2] == x ) h2[v2] = 0;
}
int Hash::Cauta(unsigned int x)
{
int v1 = (a * x + b) % MOD;
int v2 = (b * x + c*c) % MOD;
if(h1 [v1] == x) return 1;
if(h2 [v2] == x ) return 1;
return 0;
}
void Hash::Citeste ()
{
int n, caz, i;
unsigned int x;
int ok = 0;
while (ok == 0)
{
ok = 1;
FILE *f = fopen ("hashuri.in", "r");
FILE *fi = fopen ( "hashuri.out", "w");
fscanf (f,"%d", &n);
memset(h1,0,size_h);
memset(h2,0,size_h);
SetHash();
for (i = 1; i <= n && ok; i++)
{
fscanf (f, "%d %d", &caz, &x);
switch (caz)
{
case 1: if(!Insereaza(x))
{
ok = 0;
}
break;
case 2: Del(x); break;
case 3: fprintf( fi,"%d\n", Cauta(x)); break;
}
}
fclose(f);
fclose(fi);
}
}
int main()
{
srand (time(NULL));
Hash H(1000000);
H.Citeste ();
return 0;
}