Pagini recente » Cod sursa (job #2173952) | Cod sursa (job #632343) | Cod sursa (job #1972382) | rocky1 | Cod sursa (job #761108)
Cod sursa(job #761108)
#include <stdlib.h>
#include <stdio.h>
#define M ((int) 1000000) //dimensiunea tabelului
#define A ((float) 0.618034f)//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 (N--) {
fscanf(in, "%d %d", &op, &x);
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;
}