Cod sursa(job #761104)

Utilizator whoasdas dasdas who Data 24 iunie 2012 19:07:56
Problema Hashuri Scor 40
Compilator c Status done
Runda Arhiva educationala Marime 1.56 kb
#include <stdlib.h>
#include <stdio.h>

#define M ((int) 1000000)	//dimensiunea tabelului
#define A ((float) 0.618034)//magic number (Knuth);

struct node {
	int x;
	struct node *next;
};
typedef struct node node;

node* T[M];

/*************************************************************************/

void assert(int cond) {
	if (!cond) {
		printf("Assertion failed!");
		exit(1);
	}
}

int list_find(node* head, int x) {
	node* i;
	for (i = head; i; i = i->next) {
		if (i->x == x) {
			return 1;
		}
	}
	return 0;

}

void list_insert(node** head, int x) {
	if (!list_find(*head, x)) {
		node *tmp = *head;
		*head = malloc(sizeof (node));
		(*head)->x = x;
		(*head)->next = tmp;
	}
}

void list_delete(node** head, int x) {
	node *i, *prev = NULL;
	for (i = *head; i; i = i->next) {
		if (i->x == x) {
			if (prev == NULL) {
				assert(i == *head);
				*head = (*head)->next;
				free(i);
			} else {
				prev->next = i->next;
				free(i);
			}
		}
		prev = i;
	}
}

int hash(int x) {
	int h = M * (A*x - (int)(A*x));
	assert(0 < h && h < M);
	return h;
}

void hash_delete(int x) {
	list_delete(&T[hash(x)], x);
}

void hash_insert(int x) {
	list_insert(&T[hash(x)], x);
}

int hash_contains(int x) {
	return list_find(T[hash(x)], x);
}

int main() {
	FILE* in = fopen("hashuri.in", "r");
	FILE* out = fopen("hashuri.out", "w+");
	int N, op, x;
	fscanf(in, "%d", &N);

	while( fscanf(in, "%d %d", &op, &x) == 2) {
		switch (op) {
		case 1: hash_insert(x); break;
		case 2: hash_delete(x); break;
		case 3: fprintf(out, "%d\n", hash_contains(x)); break;
		}
	}

	fclose(out);

	return 0;
}