Cod sursa(job #977815)

Utilizator caen1c a e n caen1 Data 26 iulie 2013 18:29:26
Problema Hashuri Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.3 kb
#include <stdio.h>
#include <stdlib.h>

#define NMAX 666013

typedef struct lista lista;

struct lista {
    unsigned long val;
    lista *next;
};

lista *Hash[NMAX];

int
h(unsigned long x) {
    return x % NMAX;
}

void
add(unsigned long x)
{
    lista *nod;

    for (nod = Hash[h(x)]; nod && nod->val != x; nod = nod->next)
        ;

    if (nod == NULL) {
        nod = malloc(sizeof(lista));
        nod->val = x;
        nod->next = Hash[h(x)];
        Hash[h(x)] = nod;
    }
}

void
delete(unsigned long x)
{
    lista *nod, *prev;

    for (prev = NULL, nod = Hash[h(x)]; nod && nod->val != x; prev = nod, nod = nod->next)
        ;

    if (nod) {
        if (prev)
            prev->next = nod->next;
        else
            Hash[h(x)] = nod->next;
        free(nod);
    }
}

unsigned short
search(unsigned long x)
{
    lista *nod;

    for (nod = Hash[h(x)]; nod && nod->val != x; nod = nod->next)
        ;

    if (nod)
        return 1;
    return 0;
}

int
main(void)
{
    unsigned long n, x;
    unsigned short op;

    freopen("hashuri.in", "r", stdin);
    freopen("hashuri.out", "w", stdout);

    scanf("%lu", &n);

    while (n--) {
        scanf("%hu %lu", &op, &x);

        if (op == 1) add(x);
        else if (op == 2) delete(x);
        else printf("%hu\n", search(x));
    }

    return 0;
}