Cod sursa(job #1756716)

Utilizator dtoniucDaniel Toniuc dtoniuc Data 13 septembrie 2016 15:19:23
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>

#define BIG_PRIME 666013

using namespace std;

typedef struct node
{
	int value;
	struct node *next;
}Node;

int ComputeHash(int x);
bool Find(int x, Node** map);
void Insert(int x, Node** map);
void Erase(int x, Node** map);

int main()
{
    ifstream fin;
    ofstream fout;
    fout.open("hashuri.out");
    fin.open("hashuri.in");

    int n, tip, x;
    Node** map = new Node*[BIG_PRIME - 1]();

    fin >> n;
    for(int i = 1; i <= n; i++)
    {
    	fin >> tip >> x;
    	switch(tip)
    	{
    		case 1 :
    			if(!Find(x, map))
    				Insert(x, map);
    			break;
    		case 2 :
    			if(Find(x, map))
    				Erase(x, map);
    			break;
    		case 3 :
    			if(Find(x, map))
    				fout << "1\n";
    			else
    				fout << "0\n";
    			break;
    		default :
    			exit(1);
    	}
    }

    fin.close();
    fout.close();
    return 0;
}

int ComputeHash(int x)
{
	return x % BIG_PRIME;
}

bool Find(int x, Node** map)
{
	int key = ComputeHash(x);

	bool found = false;
	Node* current = map[key];
	while(current)
	{
		if(current->value == x)
		{
			found = true;
			break;
		}

		current = current -> next;
	}

	return found;
}

void Insert(int x, Node** map)
{
	int key = ComputeHash(x);

	Node* newNode = new Node();
	newNode->value = x;
	newNode->next = map[key];

	map[key] = newNode;
}

void Erase(int x, Node** map)
{
	int key = ComputeHash(x);

	Node* current = map[key];
	if(current->value == x)
	{
		map[key] = current->next;
		delete current;
	}
	else
	{
		Node* prev = current;
		current = current->next;

		while(current->value != x)
		{
			prev = current;
			current = current->next;
		}

		prev->next = current->next;
		delete current;
	}
}