Cod sursa(job #1395061)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 20 martie 2015 23:24:07
Problema Hashuri Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <stdio.h>
#include <stdlib.h>

#define MAGIC 0x01000193
#define h(x) ((x) % MAGIC)

typedef struct _list {
    unsigned val;
    struct _list *next;
} list;

list *hash[MAGIC];

int main (void) {
    FILE *f, *g;
    char op_type;
    list *aux, *tmp;
    unsigned query, x, hx;

    f = fopen("hashuri.in", "r");
    fscanf(f, "%u ", &query);
    g = fopen("hashuri.out", "w");
    while (query--) {
        fscanf(f, "%c%u ", &op_type, &x);
        hx = h(x);
        tmp = NULL;
        aux = hash[hx];
        if (op_type == '1') {
            if(hash[hx] == NULL) {
                hash[hx] = (list *) malloc(sizeof(list));
                hash[hx]->val = x;
                hash[hx]->next = NULL;
            } else {
                while (aux != NULL && aux->val != x) {
                    tmp = aux;
                    aux = aux->next;
                }
                if(aux == NULL) {
                    aux = (list *) malloc(sizeof(list));
                    aux->val = x;
                    aux->next = NULL;
                    tmp->next = aux;
                }
            }
        } else if (op_type == '2') {
            while (aux != NULL && aux->val != x) {
                tmp = aux;
                aux = aux->next;
            }
            if(aux != NULL) {
                if (aux == hash[hx]) {
                    hash[hx] = NULL;
                    free(aux);
                }
                else {
                    if(aux->next != NULL)
                        tmp->next = aux->next;
                    aux = NULL;
                    free(aux);
                }
            }
        } else {
            while (aux != NULL && aux->val != x) {
                aux = aux->next;
            }
            fputs((aux == NULL) ? "0\n" : "1\n", g);
        }
    }
    fclose(f);
    fclose(g);
    return 0;
}