Cod sursa(job #2939554)

Utilizator rastervcrastervc rastervc Data 13 noiembrie 2022 21:39:17
Problema Hashuri Scor 70
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.27 kb
#include <stdio.h>
#include <stdlib.h>

#define LIM 1000000

// ---------------- SINGLY-LINKED LIST ---------------

struct _Node {
	struct _Node *next;
	int value;
};
typedef struct _Node Node;

static inline Node *node_init(Node *next, int value) {
	Node *node = (Node *)malloc(sizeof(Node));
	node->next = next;
	node->value = value;
	return node;
}

// ----------------- HASHTABLE ----------------

typedef Node **HashTable;

static inline size_t hashf(int value) {
	return ((size_t)value) % LIM;
}

static inline HashTable hashtable_init() {
	HashTable ht = (Node **)malloc(LIM * sizeof(Node *));
	for (int i = 0; i < LIM; i++)
		ht[i] = NULL;
	return ht;
}

static inline void hashtable_insert(HashTable ht, int value) {
	const size_t hash = hashf(value);
	
	Node *node = ht[hash];

	int found = 0;
	while (!found && node != NULL) {
		if (node->value == value)
			found = 1;
		node = node->next;
	}

	if (!found) ht[hash] = node_init(ht[hash], value);
}

static inline void hashtable_erase(HashTable ht, int value) {
	const size_t hash = hashf(value);

	if (ht[hash] == NULL) return;
	if (ht[hash]->value == value) {
		free(ht[hash]);
		ht[hash] = NULL;
		return;
	}

	Node *node = ht[hash];
	while (node->next != NULL && node->next->value != value)
		node = node->next;
		
	if (node->next != NULL) {
		free(node->next);
		node->next = node->next->next;
	}
}

static inline int hashtable_find(HashTable ht, int value) {
	const size_t hash = hashf(value);
	
	Node *node = ht[hash];
	int found = 0;

	while (!found && node != NULL) {
		if (node->value == value)
			found = 1;
		node = node->next;
	}

	return found;
}

static inline void hashtable_free(HashTable ht) {
	for (int i = 0; i < LIM; i++)
		free(ht[i]);
	free(ht);
}

int main(void) {
	freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);

	HashTable ht = hashtable_init();
	int N, i, operation, value;

	scanf("%d", &N);
	for (i = 0; i < N; i++) {
		scanf("%d%d", &operation, &value);

		if (operation == 1) 
			hashtable_insert(ht, value);
		else if (operation == 2) 
			hashtable_erase(ht, value);
		else printf("%i\n", hashtable_find(ht, value));
	}

	hashtable_free(ht);

	fclose(stdout);
	fclose(stdin);
	return 0;
}