Cod sursa(job #982797)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 10 august 2013 00:36:08
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 kb
#include <fstream>
#include <list>
#include <ctime>
#include <cstdlib>

const unsigned MOD = 666013;

class Hash 
{
	std::list<unsigned> *nArr;
	unsigned size;
	unsigned table;
	unsigned a;
	unsigned b;
	
	unsigned getHash(unsigned key)
	{
		return ((a * key + b) % MOD) % table;	
	}
	
public:
	Hash() : size(0), table(666013), a(rand() % (MOD - 1) + 1), b(rand() % MOD), nArr(new std::list<unsigned>[666013])
	{ }
	
	~Hash()
	{
		delete[] nArr;
	}
	
	bool find(unsigned key)
	{
		for(std::list<unsigned>::iterator it = nArr[getHash(key)].begin(); it != nArr[getHash(key)].end(); it++)
			if (*it == key) return true;
		return false;
	}
	
	void insert(unsigned key) 
	{
		if(find(key)) return;
		size++;
		if(table == size)
		{
			std::list<unsigned> *cArr = new std::list<unsigned>[table * 2];
			table *= 2;
			a = rand() % (MOD - 1) + 1;
			b = rand() % MOD;
			for(unsigned i = 0; i < table / 2; i++)
			{
				while(!nArr[i].empty())
				{
					unsigned cKey = nArr[i].front();
					nArr[i].pop_front();
					cArr[getHash(cKey)].push_back(cKey);
				}
			}
			cArr[getHash(key)].push_back(key);
			delete[] nArr;
			nArr = cArr;
			cArr = NULL;
		}
		else nArr[getHash(key)].push_back(key);
	}
	
	void deletes(unsigned key)
	{
		if(!find(key)) return;
		size--;
		if(table / 4 >= size && table > 666013)
		{
			std::list<unsigned> *cArr = new std::list<unsigned>[table * 2];
			table /= 2;
			a = rand() % (MOD - 1) + 1;
			b = rand() % MOD;
			for(unsigned i = 0; i < table * 2; i++)
			{
				while(!nArr[i].empty())
				{
					unsigned cKey = nArr[i].front();
					nArr[i].pop_front();
					if(cKey != key) cArr[getHash(cKey)].push_back(cKey);
				}
			}
			delete[] nArr;
			nArr = cArr;
			cArr = NULL;
		}
		else nArr[getHash(key)].remove(key);
	}	
};

int main()
{
	srand(time(NULL));
	std::ifstream in("hashuri.in");
	std::ofstream out("hashuri.out");
	Hash myH;
	unsigned nV, a;
	unsigned b;
	in >> nV;
	for(unsigned i = 0; i < nV; i++)
	{
		in >> a >> b;
		if(a == 1) myH.insert(b);
		else if(a == 2) myH.deletes(b);
		else out << myH.find(b) << '\n';
	}
	return 0;
}