Cod sursa(job #2728335)

Utilizator om6gaLungu Adrian om6ga Data 23 martie 2021 05:10:35
Problema Hashuri Scor 0
Compilator c-32 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <stdio.h>
#include <string.h>

int i, j, N;
unsigned int *hashtable[512];

unsigned int lowbias32(unsigned int x) {
    x ^= x >> 16;
    x *= 0x7feb352d;
    x ^= x >> 15;
    x *= 0x846ca68b;
    x ^= x >> 16;
    return x;
}

void op_add(unsigned int index, unsigned int n) {
	unsigned int *bucket = hashtable[index];
	unsigned int bucket_size = bucket[0];
	unsigned int nr_elem = bucket[1];
	//printf("i = %d, index = %d, size = %d\n", i, index, hashtable[index][0]);
	if (nr_elem == bucket_size - 2) {
		//printf("index %d resizing from %d to %d\n", index, hashtable[index][0], j<<1);
		hashtable[index] = realloc(bucket, bucket_size<<3);
		memset(hashtable[index] + bucket_size, 0, bucket_size);
		hashtable[index][bucket_size] = n;
		hashtable[index][0] <<= 1;
		hashtable[index][1]++;
		return;
	}
	for (j = 2; j < bucket_size && nr_elem; j++) {
		if (0 == bucket[j]) {
			bucket[j] = n;
			hashtable[index][1]++;
			return;
		}
		nr_elem--;
	}
}

void op_remove(unsigned int index, unsigned int n) {
	unsigned int *bucket = hashtable[index];
	unsigned int bucket_size = bucket[0];
	unsigned int nr_elem = bucket[1];
	for (j = 1; j < bucket_size && nr_elem; j++) {
		if (n == bucket[j]) {
			bucket[j] = 0;
			nr_elem--;
			return;
	    }
	    if (!bucket[j]) {
	    	nr_elem--;
		}
	}
}

void op_question(unsigned int index, unsigned int n) {
	unsigned int *bucket = hashtable[index];
	unsigned int bucket_size = bucket[0];
	for (j = 1; j < bucket[0]; j++) {
		if (n == bucket[j]) {
			printf("1\n");
			return;
		}
	}
	if (j == bucket[0]) {
		printf("0\n");
	}
}

void main() {
	unsigned int n, o, flag;
	freopen("hashuri.in", "r", stdin);
	freopen("hashuri.out", "w", stdout);
	unsigned int index;
	void *op_fct[] = {op_add, op_remove, op_question};
	
	for (i = 0; i < 512; i++) {
		hashtable[i] = calloc(1300, sizeof(unsigned int));
		hashtable[i][0] = 1300;
	}   
	
	scanf("%d", &N);
	i = N;
	while (1) {
		i--;
		scanf("%u %u", &o, &n);
		index = (lowbias32(n) & 0x1ff);
		((void (*)(unsigned int, unsigned int))op_fct[o-1])(index, n);
		if (i == 0)
	        break;
	}

	return;
}