Cod sursa(job #708360)

Utilizator DraStiKDragos Oprica DraStiK Data 6 martie 2012 19:11:56
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.39 kb
#include <cstdlib>
#include <cstdio>
#include <ctime>
using namespace std;

#define DEL -1
#define NIL 0

class hash_table {

  int hash_size;
  int *T;

  int max_octet,size_octet;
  int *a1,*a2;

  int h1 (int key) {
    int i,ret;

      ret=0;
      for (i=0; i<max_octet; ++i) {

        ret=(ret+(key&((1<<this->size_octet)-1))*this->a1[i])%this->hash_size;
        key>>=this->size_octet;

        if (!key)
          break ;
      }

      return ret;
  }

  int h2 (int key) {
    int i,ret;

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

        ret=(ret+(key&((1<<this->size_octet)-1))*this->a2[i])%this->hash_size;
        key>>=this->size_octet;

        if (!key)
          break ;
      }

      return ret;
  }

  int h (int key,int poz) {

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

  public:
  hash_table (int hash_size,int max_octet,int size_octet) {
    int i;

    this->hash_size=hash_size;
    this->T=new int[hash_size];

    this->max_octet=max_octet;
    this->size_octet=size_octet;
    this->a1=new int[max_octet];
    this->a2=new int[max_octet];

    for (i=0; i<max_octet; ++i) {

      this->a1[i]=rand ()%hash_size;
      this->a2[i]=rand ()%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;
        return ;
      }
    }
  }

  void erase (int key) {
    int is;

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

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

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

  hash_table Hash (1000003,8,4);
  int T,i,x,tip;

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

    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;
}