Cod sursa(job #744736)

Utilizator JohannesJohannes Dragulanescu Johannes Data 9 mai 2012 16:08:03
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
//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;
		
	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;
		}
		
		
		int hash_function(int x, int i)
		{
			int rez=abs((x%NMAX+rand1*i+rand2*i*i))%NMAX;
			return rez;
		}
		
		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;
		}
		
		void afisare ()
		{
			cout<<"V= ";
			for (int i=0;i<NMAX;++i)
				cout<<v[i]<<' ';
			cout<<endl;
		}
};

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;
}