Cod sursa(job #1413558)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 1 aprilie 2015 22:30:44
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <stdio.h>
#include <stdlib.h>

#define MAGIC 0xA299D
#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 = hash[hx];
    aux = hash[hx];
    if (op_type == '1') {  // inserare
      if(hash[hx] == NULL) { // nu exista in sir
        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) { // nu exista in sir
          aux = (list *) malloc(sizeof(list));
          aux->val = x;
          aux->next = NULL;
          tmp->next = aux;
        }
      }
    } else if (op_type == '2') { // eliminare
      while (aux != NULL && aux->val != x) {
        tmp = aux;
        aux = aux->next;
      }
      if (aux != NULL) {
        if (aux == hash[hx]) {
          hash[hx] = aux->next;
        } else {
          if (aux->next != NULL)
            tmp->next = aux->next;
        }
        free(aux);
        aux = NULL;
      }
    } else { // cautare
      while (aux != NULL && aux->val != x) {
        aux = aux->next;
      }
      fputs((aux == NULL) ? "0\n" : "1\n", g);
    }
  }
  fclose(f);
  fclose(g);
  return 0;
}