Cod sursa(job #525830)

Utilizator icepowdahTudor Didilescu icepowdah Data 26 ianuarie 2011 14:48:36
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
using namespace std;

#define HASH_TABLE_SIZE 666013

struct node {
	int data;
	node* next;
	node* prev;
};

enum op {ADD=1, DELETE, SEARCH};

node* searchTable(int elem, int hashVal, node* hash[]);

int main(void)
{
	int n, i, elem, currOp, hashVal;

	node* hash[HASH_TABLE_SIZE];
	for (i=0;i<HASH_TABLE_SIZE;i++) 
	{
		hash[i] = NULL;
	}

	ifstream f("hashuri.in");
	ofstream g("hashuri.out");
	f >> n;
	
	for (i=0;i<n;i++)
	{
		f >> currOp;
		f >> elem;

		hashVal = elem % HASH_TABLE_SIZE;
		node* ptr = searchTable(elem,hashVal,hash);

		switch(currOp)
		{
		case ADD:
			if (ptr == NULL)
			{
				node* nod = new node;
				nod->data = elem;
				nod->prev = NULL;
				nod->next = hash[hashVal];
				if (hash[hashVal] != NULL)
				{
					hash[hashVal]->prev = nod;
				}
				hash[hashVal] = nod;
			}
			break;
		case DELETE:
			if (ptr != NULL)
			{
				if (ptr->prev == NULL)
				{
					hash[hashVal] = ptr->next;
				}
				else
				{
					ptr->prev->next = ptr->next;
					if (ptr->next != NULL)
					{
						ptr->next->prev = ptr->prev;
					}
				}
				delete ptr;
			}
			break;
		case SEARCH:
			
			if (ptr != NULL)
			{
				g << "1\n";
			}
			else g << "0\n";
			break;
		}
	}

	f.close();
	g.close();
	return 0;
}

node* searchTable(int elem, int hashVal, node* hash[])
{
	node* ptr = hash[hashVal];
	while (ptr != NULL && ptr->data != elem)
	{
		ptr = ptr->next;
	}
	return ptr;
}