Cod sursa(job #712018)

Utilizator sana1987Laurentiu Dascalu sana1987 Data 12 martie 2012 22:36:15
Problema Hashuri Scor 70
Compilator c Status done
Runda Arhiva educationala Marime 2.09 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int N, n, c;

typedef struct node_t {
    int x;
    struct node_t *next;
} node;

node *hashtable[666013];

int hash(int x) {
    return x % 666013;
}

void hash_insert(int x) {
    int xhash = hash(x);
    if (hashtable[xhash] == NULL) {
        hashtable[xhash] = (node *)malloc(sizeof(node));
        hashtable[xhash]->x = x;
        hashtable[xhash]->next = NULL;
    }
    else {
        node *aux = hashtable[xhash];
        node *tmp = (node *)malloc(sizeof(node));
        tmp->x = x;
        tmp->next = NULL;
        while (aux->next) {
            aux = aux->next;
        }
        aux->next = tmp;
    }
}

void hash_delete(int x) {
    int xhash = hash(x);
    node *tmp = hashtable[xhash];
    if (tmp) {
        if (tmp->x == x) {
            hashtable[xhash] = tmp->next;
        }
        else {
            node *prev = tmp;
            tmp = tmp->next;
            if (tmp) {
                while (tmp->next) {
                    if (tmp->x == x) {
                        prev->next = NULL;
                    }
                    prev = prev->next;
                    tmp = tmp->next;
                }
            }
            else {
                if (prev->x == x) {
                    hashtable[xhash] = NULL;
                }
            }
        }
    }
}

int hash_exists(int x) {
    int xhash = hash(x);
    int result = 0;
    node *tmp = hashtable[xhash];
    if (tmp) {
        while(tmp) {
            if (tmp->x == x) {
                result = 1;
                break;
            }
            tmp = tmp->next;
        }
    }

    return result;
}

int main(int argc, char **argv) {
    freopen("hashuri.in", "r", stdin);
    freopen("hashuri.out", "w", stdout);

    memset(hashtable, 0, sizeof(hashtable));;
    
    scanf("%d", &N);
    int i;

    for (i = 0; i < N; i++) {
        scanf("%d %d", &c, &n);
        if (c == 1) {
            hash_insert(n);
        }
        else if (c == 2) {
            hash_delete(n);
        }
        else {
            printf("%d\n", hash_exists(n));
        }

    }

    
	return 0;
}