Cod sursa(job #860741)

Utilizator GagosGagos Radu Vasile Gagos Data 20 ianuarie 2013 18:41:35
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <cstdio>
#include <cstdlib>

#define MOD 666013

struct Node {
  int value;
  Node* next;

  Node() : value(0), next(NULL) { }
  Node(int value) : value(value), next(NULL) { }
  Node(int value, Node* next) : value(value), next(next) { }
};

class Hash {
public:
  Hash();

  void add(int value);
  void remove(int value);
  int exists(int value);

private:
  int count;
  Node* hash[MOD];

  void init_hash();
};

Hash::Hash() {
  this->count = 0;
  
  init_hash();
}

void Hash::add(int value) {
  int index = value % MOD;
  Node* node = new Node(value, this->hash[index]);

  this->hash[index] = node;
  this->count += 1;
}

int Hash::exists(int value) {
  int index = value % MOD;

  for (Node* node = this->hash[index]; node != NULL; node = node->next) {
    if (node->value == value) {
      return 1;
    }
  }

  return 0;
}

void Hash::remove(int value) {
  int index = value % MOD;
  Node* node = this->hash[index];
  Node* prev = node;

  if (this->count == 0 || node == NULL) {
    return;
  } 
  
  if (node->value == value) {
    this->hash[index] = this->hash[index]->next;
    this->count -= 1;

    delete node;

    return;
  }

  for (prev = node, node = node->next; node != NULL; prev = node, node = node->next) {
    if (node->value == value) {
      prev->next = node->next;
      this->count -= 1;

      delete node;

      return;
    }
  }
}

void Hash::init_hash() {
  for (int i = 0; i < MOD; ++i) {
    this->hash[i] = NULL;
  }
}

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

  int n;
  Hash* hash = new Hash();

  scanf("%d", &n);

  while (n--) {
    int op, val;

    scanf("%d %d", &op, &val);

    if (op == 1) {
      hash->add(val);
    } else if (op == 2) {
      hash->remove(val);
    } else if (op == 3) {
      printf("%d\n", hash->exists(val));
    }
  }

  delete hash;

  fcloseall();

  return 0;
}