Cod sursa(job #687056)

Utilizator mika17Mihai Alex Ionescu mika17 Data 22 februarie 2012 01:46:45
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
using std::string;
using std::vector;

template <typename T>
class hash
{
private:
	const static unsigned TABLE_SIZE = 1u << 2u;
	vector< vector<T> > table;
	unsigned h(T key)
	{
		return (int)floor( TABLE_SIZE * (0.6180340 * key - floor(0.6180340 * key) ) );
	}
	typename vector<T>::iterator search(T key)
	{
		for(typename vector<T>::iterator i = table[h(key)].begin() ; i != table[h(key)].end(); ++i)
			if(*i == key)
				return i;
		return table[h(key)].end();
	}
public:
	hash() : table(vector< vector<T> >(TABLE_SIZE)) {}
	bool insert(T key)
	{
		unsigned x = h(key);
		if(search(key) == table[h(key)].end() )
		{
			table[h(key)].push_back(key);
			return true;
		}

		return false;
	}
	bool remove(T key)
	{
		typename vector<T>::iterator i = search(key);
		if(i != table[h(key)].end())
		{
			table[h(key)].erase(i);
			return true;
		}
		return false;
	}
	bool find(T key)
	{
		return search(key) != table[h(key)].end();
	}
};

int main()
{
	std::ifstream in("hashuri.in");
	std::ofstream out("hashuri.out");

	unsigned N;
	in >> N;

	char code;
	unsigned long long key;
	hash<unsigned long long> h;
	while(N--)
	{
		in >> code >> key;
		in.ignore();
		switch(code)
		{
		case '1':
			h.insert(key);
			break;
		case '2':
			h.remove(key);
			break;
		case '3':
			out << h.find(key) << '\n';
			break;
		}
	}
}