Cod sursa(job #1651713)

Utilizator Mihai22eMihai Ionut Enache Mihai22e Data 13 martie 2016 19:05:37
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <cstdio>
using namespace std;

class HasherForInt {
	private:
		static const int MOD = 666013;

	public:
		static const int numberOfBuckets() {
			return MOD;
		}

		int operator() (int value) const {
			return value % MOD;
		}
};

template <class T>
class Node {
	public:
		T value;
		Node *next;
		
		Node() {
			next = NULL;
		}

		Node(T value) {
			this->value = value;
			next = NULL;
		}

		~Node() {
			if(this->next == NULL) {
				return;
			}
			else {
				delete this->next;
			}
		}
};

template <class T, class Hasher>
class HashTable {
	private:
		Node <T> **hashTable = new Node <T>* [Hasher::numberOfBuckets()];
	public:
		void insertValue(int value) {
			int list = Hasher()(value);
			
			if(hashTable[list] == NULL) {
				hashTable[list] = new Node <T> (value);
			}
			else {
				Node <T> *node = hashTable[list];
				
				while(node->next != NULL) {
					if(node->value == value) {
						return;
					}
					node = node->next;
				}

				Node <T> *newNode = new Node <T> (value);
				node->next = newNode;
			}
		}

		void deleteValue(int value) {
			int list = Hasher()(value);

			if(hashTable[list] == NULL) {
				return;
			}
			else {
				if(hashTable[list]->value == value) {
					Node <T> *tmp = hashTable[list];
					hashTable[list] = tmp->next;
					delete tmp;
				}
				else {
					Node <T> *node = hashTable[list];
					
					while(node->next != NULL && node->next->value != value) {
						node = node->next;
					}

					if(node->next != NULL) {
						Node <T> *tmp = node->next;
						node->next = node->next->next;
						delete tmp;
					}
				}
			}
		}

		bool searchValue(int value) {
			int list = Hasher()(value);
			
			Node <T> *node = hashTable[list];
			
			while(node != NULL && node->value != value) {
				node = node->next;
			}

			if(node != NULL) {
				return true;
			}
			else {
				return false;
			}
		}

		~HashTable() {
			delete[] this->hashTable;
		}
};

int main() {
	freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);
	
	int n;
	scanf("%d", &n);
	
	HashTable <int, HasherForInt> h;
	for(int i = 0; i < n; ++i) {
		int op, x;
		scanf("%d %d", &op, &x);
		
		if(op == 1) {
			h.insertValue(x);
		}
		else if(op == 2) {
			h.deleteValue(x);
		}
		else {
			printf("%d\n", h.searchValue(x));
		}
	}

	fclose(stdin);
	fclose(stdout);
	
	return 0;
}