Cod sursa(job #956226)

Utilizator sorin2kSorin Nutu sorin2k Data 2 iunie 2013 15:56:19
Problema Hashuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include<fstream>
#define MAX 100003
using namespace std;

ifstream fin("hashuri.in");
ofstream fout("hashuri.out");

struct Nod {
	int data;
	Nod *next;
};

Nod *tab[MAX];
int n, i, op, val;

int h(int x)
{
	int sum = 0;
	while(x)
	{
		sum += x % 10;
		x = x / 10;
	}
	return sum % MAX;
}

int search(int x)
{
	int poz = h(x);
	Nod *t = tab[poz];
	while(t != 0)
	{
		if(t->data == x)
			return 1;
		t = t->next;
	}
	return 0;
}

void insert(int x)
{
	if(search(x) == 0)
	{
		int poz = h(x);
		Nod *nod = new Nod; 
		nod->data = x;
		if(tab[poz] == 0) // daca lista e goala
		{
			tab[poz] = nod;
			tab[poz]->next = 0;
		}
		else
		{
			nod->next = tab[poz]->next;
			tab[poz]->next = nod;
		}			
	}
}

void del(int x)
{
	int poz = h(x);
	Nod *t = tab[poz];
	if(t != 0)
	{
		if(t->data == x) // daca e primul element, modificam direct hash[poz]
			tab[poz] = t->next;
		else
		{
			Nod *p = t; // = hash[poz], va fi nodul din spate
			t = t->next;
			while(t != 0 && t->data != x)
			{
				t = t->next;
				p = p->next;
			}
			if(t != 0) // am gasit nodul care il contine pe x
			{
				p->next = t->next;
				delete t;
			}
		}
	}
}

int main()
{
	fin >> n;
	for(i = 0; i < n; i++)
	{
		fin >> op >> val;
		switch(op)
		{
		case 1:
			insert(val);
			break;
		case 2:
			del(val);
			break;
		case 3:
			fout << search(val) << endl;
		}
	}
	return 0;
}