Cod sursa(job #2736231)

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

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

class HashTable {
private:
	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);
		if (table[idx] == nullptr)
		{
			table[idx] = n;
		}
		else
		{
			Node* temp = table[idx];
			while (temp->val != x && temp->next != nullptr)
			{
				temp = temp->next;
			}
			if (temp->val != x)
				temp->next = 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;
	}
};

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