Cod sursa(job #614591)

Utilizator vladbagrinVlad Bagrin vladbagrin Data 6 octombrie 2011 21:20:29
Problema Hashuri Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 1.82 kb
#include <stdio.h>
#include <stdlib.h>

#define INPUT "hashuri.in"
#define OUTPUT "hashuri.out"
#define MAX_LEN 1000000
#define MAX_NUM 2000000000
#define SUCCESS 0

typedef struct node_str {
	int value;
	struct node_str* next;
} node;

void add(node *head, int value) {
	node *new_tip = (node*) malloc(sizeof(node));
	new_tip->value = value;
	new_tip->next = NULL;
	
	node* p = head;
	while (p->next) {
		p = p->next;
	}
	p->next = new_tip;
}

void delete(node *head, int value) {
	node* p = head;
	while (p->next && p->next->value != value) {
		p = p->next;
	}
	if (p->next) {
		node *tmp = p->next;
		p->next = p->next->next;
		free(tmp);
	}
}

int find(node* head, int value) {
	node* p = head->next;
	while (p && p->value != value) {
		p = p->next;
	}
	return p != NULL;
}

void free_all(node* head) {
	if (head) {
		free_all(head->next);
		free(head);
	}
}

void init_hash(node* h, int n) {
	int i;
	for (i = 0; i < n; i++) {
		h[i].next = NULL;
	}
}

void free_hash(node* h, int n) {
	int i;
	for (i = 0; i < n; i++) {
		free_all(h[i].next);
	}
}

void hash_add(node* h, int n, int value) {
	add(&h[value % n], value);
}

void hash_delete(node* h, int n, int value) {
	delete(&h[value % n], value);
}

int hash_find(node* h, int n, int value) {
	return find(&h[value % n], value);
}

int main() {
	FILE *f = fopen(INPUT, "r");
	FILE *o = fopen(OUTPUT, "w");
	int n, i;
	int io_result;
	io_result = fscanf(f, "%d", &n);
	node* h = (node*) malloc(n * sizeof(node));
	init_hash(h, n);
	
	for (i = 0; i < n; i++) {
		int type;
		int value;
		io_result = fscanf(f, "%d %d", &type, &value);
		switch (type) {
			case 1:
				hash_add(h, n, value);
				break;
			case 2:
				hash_delete(h, n, value);
				break;
			case 3:
				fprintf(o, "%d\n", hash_find(h, n, value));
				break;
		}
	}
	
	free_hash(h, n);
	free(h);
	fclose(f);
	fclose(o);
	return SUCCESS;
}