Cod sursa(job #281870)

Utilizator tomescu_alinTomescu Alin tomescu_alin Data 16 martie 2009 08:42:01
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.43 kb
#include <iostream>
#include <fstream>
#include <list>
#include <algorithm>
using namespace std;

typedef unsigned char byte;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;
typedef unsigned long long ulonglong;

//#define NDEBUG

#ifdef NDEBUG
#define dbg	0 && (*((ostream *) 0))
#else
#define dbg clog
#endif

template<class T>
class AbstractHashTable {
	public:
		virtual void add(T value) 	= 0;
		virtual bool find(T value) 	= 0;
		virtual void erase(T value)	= 0;
};

class VectorBasedHashTable : public AbstractHashTable<ulong> {
	public:
		typedef AbstractHashTable<ulong> Base;
		typedef std::list<ulong> List;
		
	public:
		VectorBasedHashTable(uint hashNumber) 
			:	hash(hashNumber) {
			hashTable = new List[hash];
		}
		~VectorBasedHashTable() { delete [] hashTable; }
		
	public:
		virtual void add(ulong value) {
			if(!find(value)) {
				uint position = hashNumber(value);
				hashTable[position].push_back(value);
			}
		}
		
		virtual bool find(ulong value) {
			bool found = false;
			
			uint position = hashNumber(value);
			List::iterator it = std::find(hashTable[position].begin(), hashTable[position].end(), value);
			
			if(it != hashTable[position].end())
				found = true;
			
			return found;
		}
		
		virtual void erase(ulong value) {
			uint position = hashNumber(value);
			List::iterator it = std::find(hashTable[position].begin(), hashTable[position].end(), value);
			
			if(it != hashTable[position].end())
				hashTable[position].erase(it);
		}
	
	private:
		uint hashNumber(ulong number) {
			return number%hash;
		}
	
	private:
		List * hashTable;
		ulong hash;
};

int main(int argc, char * argv[]) {
	
	const char * inFile = "hashuri.in";
	const char * outFile = "hashuri.out";
	
	ifstream fin(inFile);
	ofstream fout(outFile);
	
	#ifndef NDEBUG
		if(!fin || !fout) {
			cerr << "Error opening one of \"" << inFile << "\" or \"" << outFile << "\"" << endl;
			return -1;
		}
	#endif
	
	ulong n, operation, param;
	fin >> n;
	
	VectorBasedHashTable hashTable(98317);
	
	for(ulong i = 0; i < n; i++) {
		fin >> operation >> param;
		switch(operation) {
			case 1:
				hashTable.add(param);
				break;
			case 2:
				hashTable.erase(param);
				break;
			case 3:
				fout << static_cast<uint>(hashTable.find(param)) << endl;
				break;
		}
	}
	
	fout.close();
	fin.close();
	
	return 0;

}