Cod sursa(job #2288204)

Utilizator DeleDelegeanu Alexandru Dele Data 22 noiembrie 2018 22:19:35
Problema Hashuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 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 % this->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) {//ca multime
		int key = this->getHashKey(value);
		HashNode*t = new HashNode;
		t->value = value;
		t->next = NULL;

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

		if (table[key]->value == value)
			return;

		HashNode*it;
		for (it = table[key]; it->next && it->next->value != value; it = it->next);
		it->next = t;
	}

	/*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*it;
		for (it = table[key]; it->next; it = it->next);

		it->next = t;
	}*/

	bool search(int value) {
		int key = this->getHashKey(value);
		HashNode*it;
		for (it = table[key]; it && it->value != value; it = it->next);
		return it != NULL;
	}

	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*it;
		for (it = table[key]; it->next; it = it->next)
			if (it->next->value == value)
				break;
		if (it == NULL)
			return;
		HashNode*temp = it->next;
		it->next = temp->next;
		delete temp;
	}

	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(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;
}