Cod sursa(job #710689)

Utilizator DraStiKDragos Oprica DraStiK Data 10 martie 2012 16:27:43
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.7 kb
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <ctime>
using namespace std;

#define OFFSET 2
#define DEL -1
#define NIL 0

int get_prime (int N) {
  bool *tmp;
  int i,j,prime;

  tmp=new bool[N+1];
  for (i=0; i<=N; ++i)
    tmp[i]=0;

  prime=2;
  for (i=2; i<=N; ++i)
    if (!tmp[i]) {
      prime=i;

      for (j=i; j<=N; j+=i)
        tmp[j]=1;
    }
  delete[] tmp;

  return prime;
}

class hash_table {

  int hash_size,hash_used;
  int *T;

  int h1 (int key) {

    return key%this->hash_size;
  }

  int h2 (int key) {

    return 1+key%(this->hash_size-1);
  }

  int h (int key,int poz) {

    return (this->h1 (key)+poz*this->h2 (key))%this->hash_size;
  }

  void rehash ();

  public:
  hash_table () {

    this->hash_size=get_prime (rand ()*OFFSET);
    this->hash_used=0;
    this->T=new int[this->hash_size];
  }

  hash_table (int hash_size) {

    this->hash_size=get_prime (hash_size*OFFSET);
    this->hash_used=0;
    this->T=new int[this->hash_size];
  }

  int find (int key) {
    int i,j;

    for (i=0; i<this->hash_size; ++i) {

        j=this->h (key,i);
        if (this->T[j]==key)
          return j;

        if (this->T[j]==NIL)
          return 0;
    }

    return 0;
  }

  void insert (int key) {
    int i,j,is;

    is=this->find (key);
    if (is)
      return ;

    for (i=0; i<this->hash_size; ++i) {

      j=this->h (key,i);
      if (this->T[j]==NIL || this->T[j]==DEL) {

        this->T[j]=key;

        if (++this->hash_used==this->hash_size)
          this->rehash ();
        return ;
      }
    }
  }

  void erase (int key) {
    int is;

    is=this->find (key);
    if (!is)
      return ;

    this->T[is]=DEL;
  }
};

void hash_table :: rehash () {
  int *tmp;
  int i,N;

  N=0;
  tmp=new int[this->hash_size];
  for (i=0; i<this->hash_size; ++i)
    if (this->T[i]!=NIL && this->T[i]!=DEL)
      tmp[N++]=this->T[i];

  this->hash_size=get_prime (this->hash_size*OFFSET);
  this->hash_used=0;

  delete[] this->T;
  this->T=new int[hash_size];
  for (i=0; i<N; ++i)
    this->insert (tmp[i]);
  delete[] tmp;
}


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

  //hash_table Hash (1007243);
  hash_table Hash;
  int T,i,x,tip;

  assert (scanf ("%d",&T));
  for (i=1; i<=T; ++i) {

    assert (scanf ("%d%d",&tip,&x));

    if (tip==1)
        Hash.insert (x);

    if (tip==2)
        Hash.erase (x);

    if (tip==3) {

      if (Hash.find (x))
        printf ("1\n");
      else
        printf ("0\n");
    }
  }

  return 0;
}