Cod sursa(job #1200463)

Utilizator DraStiKDragos Oprica DraStiK Data 22 iunie 2014 15:33:07
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <cstdio>
#include <cstring>
#include <cstdlib>

const int MOD = 666013;

struct nod {
  int info;
  nod *next;
};

int query(nod* hash[], int key, int value) {
  for (nod *i = hash[key]; i; i = i -> next)
    if (i -> info == value)
      return 1;

  return 0;
}

void insert(nod* hash[], int key, int value) {
  if (query(hash, key, value))
    return ;
  
  nod *tmp = new nod;
  tmp -> info = value;
  tmp -> next = hash[key];
  hash[key] = tmp;
}

void erase(nod* hash[], int key, int value) {
  if (!query(hash, key, value))
    return ;

  if (hash[key] -> info == value) {
    nod *tmp = hash[key];
    hash[key] = hash[key] -> next;
    delete tmp;
  }
  else {
    for (nod *i = hash[key], *j = hash[key] -> next; j; i = i -> next, j = j -> next)
      if (j -> info == value) {
        i -> next = j -> next;
        delete j;
        break;
      }
  }
}

int main () {
  FILE *fin, *fout;
  nod **hash;

  fin = fopen("hashuri.in", "r");
  fout = fopen("hashuri.out", "w");
  
  hash = new nod*[MOD];
  memset(hash, NULL, MOD * sizeof(nod *));

  int N; fscanf(fin, "%d", &N);
  for (int i = 0; i < N; ++i) {
    int tip, x; fscanf (fin, "%d%d", &tip, &x);

    if (tip == 1)
      insert(hash, abs(x) % MOD, x);
    else if (tip == 2)
      erase(hash, abs(x) % MOD, x);
    else
      fprintf(fout, "%d\n", query(hash, abs(x) % MOD, x));
  }

  for (int i = 0; i < MOD; ++i)
    while (hash[i]) {
      nod *tmp = hash[i];
      hash[i] = hash[i] -> next;
      delete tmp;
    }
  delete hash;

  return 0;
}