Cod sursa(job #729856)

Utilizator nalexandruIovan Alexandru Nicolae nalexandru Data 30 martie 2012 14:01:04
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#define NMax 199993
using namespace std;

fstream fin("hashuri.in",ios::in);
fstream fout("hashuri.out",ios::out);

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

Nod* a[NMax];

void adauga(int nr)
{
	int poz=nr%NMax;
	if(a[poz]==NULL)
	{
		a[poz]=new Nod;
		a[poz]->nr=nr;
		a[poz]->next=NULL;
	}
	else
	{
		//mai exista elemente pe pozitia poz
		Nod* x=a[poz];
		while(x->next!=NULL) { x=x->next; }
		x->next=new Nod;
		x->next->nr=nr;
		x->next->next=NULL;
	}
}

void sterge(int nr)
{
	int poz=nr%NMax;
	if(a[poz]!=NULL){
		if(a[poz]->nr==nr){//daca e pe prima pozitie
			if(a[poz]->next!=NULL){
				Nod *p=a[poz];
				a[poz]=a[poz]->next;
				delete p;
				return;
			}
			else{
				delete a[poz];
				a[poz]=NULL;
				return;
			}

		}
		else//a[poz]!=nr
			if(a[poz]->next!=NULL){
				Nod* x=a[poz];
				//x->next!=NULL
				while(x->next!=NULL){//merge pana la penultimul
					if(x->next->nr==nr){//am gasit numarul
						Nod*p = x->next;
						x->next=x->next->next;
						delete p;
						return;
					}
					if(x->next->next==NULL){//x - penultimul element
						if(x->next->nr==nr){
							delete x->next;
							x->next=NULL;
						}
					}
					x=x->next;
				}
			}
	}
}

bool exists(int nr)
{
	int poz=nr%NMax;
	Nod *x=a[poz];
	while(x!=NULL)
	{
		if(x->nr==nr)
			return 1;
		x=x->next;
	}
	return 0;
}

int main()
{
	int n,op,nr;
	fin>>n;
	for(int i=0;i<n;i++)
	{
		fin>>op>>nr;
		if(op==1)
			adauga(nr);
		if(op==2)
			sterge(nr);
		if(op==3)
			fout<<exists(nr)<<"\n";
	}

	return 0;
}