Cod sursa(job #2288254)

Utilizator DeleDelegeanu Alexandru Dele Data 22 noiembrie 2018 23:18:17
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <iostream>
#include <fstream>
std::ifstream f("hashuri.in");
std::ofstream g("hashuri.out");
class HashMap {
private:
	struct HashNode {
		int value;
		HashNode*next;
	};
	HashNode **table;
	int capacity;
	int getHashKey(int value) {
		return value % capacity;
	}
public:
	HashMap(int capacity) {
		this->capacity = capacity;
		table = new HashNode*[capacity];
		for (int i = 0; i < capacity; ++i)
			table[i] = NULL;
	}

	void insert(int value) {
		int key = this->getHashKey(value);

		HashNode*t = new HashNode;
		t->value = value;
		t->next = NULL;

		if (table[key] == NULL) {
			table[key] = t;
			return;
		}

		HashNode*q;
		for (q = table[key]; q->next; q = q->next)
			if (q->value == value)
				return;
		if (q->value == value)
			return;
		q->next = t;
	}

	bool search(int value) {
		int key = this->getHashKey(value);

		if (table[key] == NULL)
			return false;

		for (HashNode*q = table[key]; q; q = q->next)
			if (q->value == value)
				return true;

		return false;
	}

	void remove(int value) {
		int key = this->getHashKey(value);

		if (table[key] == NULL)
			return;

		if (table[key]->value == value) {
			HashNode*temp = table[key];
			table[key] = table[key]->next;
			delete temp;
			return;
		}

		HashNode*q;
		for (q = table[key]; q->next; q = q->next)
			if (q->next->value == value) {
				HashNode*temp = q->next;
				q = q->next->next;
				delete temp;
				return;
			}
	}
	void displayTable() {
		std::cout << "\n[Hash Table]\n";
		for (int i = 0; i < capacity; ++i) {
			std::cout << "Key: " << i << " <-> nodes: ";
			for (HashNode*it = table[i]; it != NULL; it = it->next)
				std::cout << it->value << " ";
			std::cout << "\n";
		}
		std::cout << "\n";
	}
};
int main() {
	int n;
	f >> n;
	
	HashMap* h = new HashMap(499999);

	int op, x;
	for (int i = 1; i <= n; ++i) {
		f >> op >> x;
		if (op == 1) {
			h->insert(x);
			continue;
		}
		if (op == 2) {
			h->remove(x);
			continue;
		}
		g << h->search(x) << '\n';
	}

	return 0;
}