Cod sursa(job #472458)

Utilizator robigiirimias robert robigi Data 24 iulie 2010 22:13:03
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
// Hashuri2.cpp : Defines the entry point for the console application.
//

//#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"

FILE *f=fopen("hashuri.in", "r");
FILE *g=fopen("hashuri.out", "w");


int n;

typedef struct nod
{
	int x;
	struct nod *adr;
}node;


node *l[919393];







inline int hashFunction(int i) 
{  
	return i % 919393; 
} 


int cauta(int x)
{
	int cv=x%919393;
	if (l[cv]==NULL) return 0;
	if (l[cv]->x==x) return 1;
	node *p=new node;
	p=l[cv];
	while (p->adr!=NULL)
	{
		if (p->adr->x==x) return 1;
	}
	return 0;
}


void inserare(int x)
{
	int cv=x%919393;
	node *p=new node;
	p->x=x;
	p->adr=l[cv];
	l[cv]=p;
}


void stergere(int x)
{
	int cv=x%919393;
	if (l[cv]==NULL) return;
	node *h=new node;
	if (l[cv]->x==x) 
	{
		h=l[cv]->adr;
		delete l[cv];
		l[cv]=h;
		return ;
	}
	node *p=new node;
	p=l[cv];
	while (p->adr!=NULL)
	{
		if (p->adr->x==x)
		{
			h=p->adr->adr;
			delete p->adr;
			p->adr=h;
			return;
		}
	}
	return ;
}




void deletee(int val) {
	int pos = hashFunction(val);
	
	if (l[pos] == NULL)
		return;

	node *helper;
	if (l[pos]->x == val) 
	{
		helper = l[pos]->adr;
		free(l[pos]);
		l[pos] = helper;
		return;
	}

	node *curr;
	for (curr = l[pos]; curr->adr != NULL; curr = curr->adr)
		if (curr->adr->x == val) {
			helper = curr->adr->adr;
			free(curr->adr);
			curr->adr = helper;
			return;
		}
}


int find(int val) {
	int pos = hashFunction(val);
	
	node *curr; 
	for (curr = l[pos]; curr != NULL; curr = curr->adr)
		if (curr->x == val)
			return 1;
	return 0;
}




int main()
{
	fscanf(f, "%d", &n);
	for (int i=1; i<=n; ++i)
	{
		int o, x;
		fscanf(f, "%d%d", &o, &x);
		if (o==1)
		{
			if (find(x)==0)
				inserare(x);
		}
		else
			if (o==2)
			{
				deletee(x);
			}
			else
			{
				fprintf(g, "%d\n", find(x));
			}
	}


	node *curr, *h;
	for (int i=0; i<=919392; ++i)
	{
		for (curr = l[i]; curr != NULL; curr = h) 
		{ 
			h=curr->adr;
			delete curr;
		}
	}

	return 0;
}