Pagini recente » Cod sursa (job #1813866) | Cod sursa (job #711866) | Cod sursa (job #1591130) | Cod sursa (job #2287254) | Cod sursa (job #744753)
Cod sursa(job #744753)
//Hashing Dragulanescu Val-Johannes Gr.135
//Clasa Hash
//h(x) = (h'(x) + rand1 * i + rand2 * i^2) % M
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <iostream>
#include <string.h>
#define NMAX 1000
using namespace std;
class Hash
{
private:
int rand1,rand2;
bool *sters; //vector pentru elementele sterse
int *v; //vectorul pt hashing
int n;
int hash_function(int,int);
public:
Hash (int k) //constructor
{
n=k;
//vectorul
v = new int[NMAX]; //nu pot declara static un vector mare
sters = new bool [NMAX];
memset (v,0,sizeof(v)*NMAX);
//initializam 2 valori random pt functia de hash
/* initialize random seed: */
srand ( time(NULL) );
/* generate number: */
rand1=rand()%NMAX;
rand2=rand()%NMAX;
}
~Hash () //destructor
{
delete[] v;
}
void hash_insert(int x)
{
int k=0;
while (v[hash_function(x,k)]!=0 && k<=NMAX)
k++;
if (k>=n+1)
{
cout<<"Vectorul este plin!";
return;
}
v[hash_function(x,k)]=x;
sters[hash_function(x,k)]=0;
}
void hash_delete(int x)
{
int k=0;
while (v[hash_function(x,k)]!=x && (v[hash_function(x,k)]!=0 || sters[hash_function(x,k)]==1) && k<=NMAX)
k++;
if (v[hash_function(x,k)]==0) return;
else if (k<=n)
{
v[hash_function(x,k)]=0;
sters[hash_function(x,k)]=1;
}
}
bool hash_search(int x)
{
int k=0;
while (v[hash_function(x,k)]!=x && (v[hash_function(x,k)]!=0 || sters[hash_function(x,k)]==1) && k<=NMAX)
k++;
if (k<=n && v[hash_function(x,k)]==x) return 1;
else return 0;
}
};
int Hash::hash_function(int x, int i)
{
int rez=abs((x%NMAX+rand1*i+rand2*i*i))%NMAX;
return rez;
}
int main ()
{
ifstream fin ("hashuri.in");
ofstream fout ("hashuri.out");
int op,n;
fin>>n;
Hash h(n);
int x;
for (int i=1;i<=n;i++)
{
fin>>op>>x;
if (op==1)
{
if (!h.hash_search(x))
h.hash_insert(x);
}
else if (op==2) h.hash_delete(x);
else if (op==3) fout<<h.hash_search(x)<<'\n';
}
fin.close();
fout.close();
return 0;
}