Cod sursa(job #2739660)

Utilizator vali_27Bojici Valentin vali_27 Data 9 aprilie 2021 11:03:52
Problema Hashuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <cmath>
#include <vector>

class HashTable {
private:
	struct Node {
		int val;
		Node* next;
		Node(int x) : val(x), next(nullptr) {}
	};

	std::vector<Node*> table;
	const unsigned tbl_size_exponent;

	unsigned hash(int x)
	{
		unsigned idx = 1ULL * 459727289478483 * x;
		idx >>= (32 - tbl_size_exponent);
		return idx;
	}

public:
	HashTable(unsigned size) : tbl_size_exponent(size) { table.resize((1 << size)); }
	void Add(int x)
	{
		unsigned idx = hash(x);
		Node* n = new Node(x);
		Node** temp = &table[idx];
		while (*temp != nullptr && (*temp)->val != x)
		{
			temp = &(*temp)->next;
		}
		if(*temp == nullptr)
		{
			*temp = n;
		}
	}
	bool Check(int x)
	{
		unsigned idx = hash(x);
		Node* temp = table[idx];
		while (temp != nullptr)
		{
			if (temp->val == x)
				return 1;
			temp = temp->next;
		}
		return 0;
	}

	void Delete(int x)
	{
		unsigned idx = hash(x);
		Node** temp = &table[idx];
		while (*temp != nullptr)
		{
			if ((*temp)->val == x)break;

			temp = &(*temp)->next;
		}

		if (*temp == nullptr)return;

		Node* del = *temp;
		*temp = (*temp)->next;
		delete del;
	}

	~HashTable()
	{
		for (Node*& i : table)delete i;
	}
};
 
int main()
{
	std::ifstream f("hashuri.in");
	std::ofstream g("hashuri.out");

	int n;
	f >> n;
	HashTable h(int(log2(n) + 1));

	for (int i = 0; i < n; ++i)
	{
		int tip, x;
		f >> tip >> x;

		switch (tip)
		{
		case 1: h.Add(x); break;
		case 2: h.Delete(x); break;
		case 3: g << h.Check(x) << '\n'; break;
		}
	}
}