Cod sursa(job #520561)

Utilizator mika17Mihai Alex Ionescu mika17 Data 9 ianuarie 2011 15:29:24
Problema Hashuri Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 1.76 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct element { int data; struct element* next; };
struct hash {

	struct element** storage;
	int size;
};

void hash_init(struct hash * h,int s) {

	h->size = s;
	h->storage = (struct element**)calloc(sizeof(struct element*),h->size);
	memset((void*)h->storage,0x0,sizeof(h->storage));

}

int hash_func(struct hash h,int x)
{
	return (int) (  ( (x * 0.618033) - (int)(x * 0.618033) )  * h.size );
}


char hash_find(struct hash h,int x)
{
	
	int hh = hash_func(h,x);
	struct element * i;

	for(i = h.storage[hh]; i != NULL; i = i->next)
		if(i->data == x) return 1;

	return 0;
}

void hash_insert(struct hash h,int x)
{
        int hh = hash_func(h,x);
        
	if(hash_find(h,x)) return;
	
	struct element * r = (struct element*)malloc(sizeof(struct element));
	r->data = x;
	r->next = h.storage[hh];
	h.storage[hh] = r;	
}

void hash_erase(struct hash h,int x)
{
        int hh = hash_func(h,x);
	struct element * i, *j;

	for(j = NULL, i = h.storage[hh]; i != NULL; j = i,i = i->next)
		if(i->data == x) break;
	if(i && j) { j->next = i->next; free(i); } 
	if(i && !j) { h.storage[hh] = i->next; free(i); } //first element
}

void hash_destroy(struct hash * h) {

	free(h->storage);
	h->size = 0;
}

int main()
{
	struct hash h;
	hash_init(&h,40000);
	
	freopen("hashuri.in","r",stdin);
	freopen("hashuri.out","w",stdout);	
	int N,op,x;
	scanf("%d",&N);
	
        while(N--)
        {
         scanf("%d%d",&op,&x);
         switch(op)
         {
          case 1: hash_insert(h,x); break;
          case 2: hash_erase(h,x); break;
          case 3: printf("%d\n",hash_find(h,x)); break;
         }
        }
	hash_destroy(&h);
        return 0;
}