Pagini recente » Cod sursa (job #2455070) | Cod sursa (job #3202383) | Cod sursa (job #1212771) | Cod sursa (job #2757703) | Cod sursa (job #905724)
Cod sursa(job #905724)
#include <stdio.h>
#include <stdlib.h>
struct Nod {
int val;
struct Nod *next, *prev;
};
typedef struct Nod Nod;
struct List {
int size;
Nod *start, *end;
};
typedef struct List List;
void list_add(List *l, int val) {
if(l->size == 0) {
l->start = l->end = (Nod*)(malloc(sizeof(Nod)));
l->start->val = val;
} else {
l->end->next = (Nod*)(malloc(sizeof(Nod)));
l->end->next->val = val;
l->end->next->prev = l->end;
l->end = l->end->next;
}
l->size ++;
}
void list_del(List *l, int val) {
if(l->size == 0) {
return;
} else if(l->size == 1) {
if(l->start->val == val) {
free(l->start);
l->start = l->end = NULL;
l->size --;
}
} else {
Nod *p = l->start;
while(p != NULL) {
if(p->val == val) {
if(p->prev != NULL) {
p->prev->next = p->next;
}
if(p->next != NULL) {
p->next->prev = p->prev;
}
free(p);
l->size --;
}
p = p->next;
}
}
}
int list_search(List* l, int val) {
if(l->size == 0) {
return 0;
} else if(l->size == 1) {
return l->start->val == val;
} else {
Nod *p = l->start;
while(p != NULL) {
if(p->val == val) {
return 1;
}
p = p->next;
}
return 0;
}
}
struct Hash {
List **H1;
List **H2;
int n1;
int n2;
};
typedef struct Hash Hash;
int hash_func(int n, int val) {
return val % n;
}
Hash* hash_new(int n, int m) {
Hash* h = (Hash*)(malloc(sizeof(Hash)));
h->H1 = (List**)malloc(sizeof(List*)*n);
h->H2 = (List**)malloc(sizeof(List*)*m);
int i;
for(i=0; i<n; i++) {
h->H1[i] = (List*)malloc(sizeof(List));
}
for(i=0; i<m; i++) {
h->H2[i] = (List*)malloc(sizeof(List));
}
h->n1 = n;
h->n2 = m;
return h;
}
void hash_add(Hash* h, int val) {
List *a = h->H1[hash_func(h->n1, val)], *b = h->H2[hash_func(h->n2, val)];
if(a->size > b->size) {
list_add(a, val);
} else {
list_add(b, val);
}
}
void hash_del(Hash* h, int val) {
list_del(h->H1[hash_func(h->n1, val)], val);
list_del(h->H2[hash_func(h->n2, val)], val);
}
int hash_search(Hash* h, int val) {
return list_search(h->H1[hash_func(h->n1, val)], val)
|| list_search(h->H2[hash_func(h->n2, val)], val);
}
int main() {
FILE *in = fopen("hashuri.in", "r"), *out = fopen("hashuri.out", "w");
Hash *h = hash_new(666013, 43261);
int n, op, v, i;
fscanf(in, "%d", &n);
for(i=0; i<n; i++) {
fscanf(in, "%d %d", &op, &v);
if(op == 1) {
hash_add(h, v);
} else if(op == 2) {
hash_del(h, v);
} else {
fprintf(out, "%d\n", hash_search(h, v));
}
}
return 0;
}