Cod sursa(job #1200456)

Utilizator vlad.doruIon Vlad-Doru vlad.doru Data 22 iunie 2014 15:13:46
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <cstdio>
#include <fstream>
#define HASH_SIZE 666013

using namespace std;

ifstream in("hashuri.in");
ofstream out("hashuri.out");

struct node {
  node* next;
  int info;

  node() {
    next = NULL;
    info = 0;
  }
};

bool lookup(node* hash[], int el) {
  node* list = hash[el%HASH_SIZE];

  while(list) {
    if(list->info == el)
      return true;
    list = list->next;
  }
  return false;
}

void add(node* hash[], int  el) {
  if (lookup(hash, el)) {
    return;
  }

  node* list = hash[el%HASH_SIZE];
  node* newnode = new node;
  newnode->info = el;
  newnode->next = list;
  hash[el%HASH_SIZE] = newnode;
}

void remove(node* hash[], int el) {
  if (!lookup(hash, el)) {
    return;
  }

  node* list = hash[el%HASH_SIZE];
  node* prev = list;
  while(list) {
    if (list->info == el) {
      if(prev == list) {
        hash[el%HASH_SIZE] = list->next;
        return;
      }
      prev->next = list->next;
      delete list;
      return;
    }
    list = list->next;
  }
}


int main (int argc, char const *argv[])
{
  int n;
  in>>n;
  int op, el;

  node** hash_table = new node*[HASH_SIZE];
  for(int i=0; i<n; ++i) {
    in>>op>>el;
    if (op == 1)
      add(hash_table, el);
    if (op == 2)
      remove(hash_table, el);
    if (op == 3)
      out<<lookup(hash_table, el)<<"\n";
  }

  for(int i=0; i<HASH_SIZE; ++i) {
    node* list = hash_table[i];
    node* aux;
    while(list) {
      aux = list;
      list = list->next;
      delete aux;
    }
  }

  delete hash_table;

  return 0;
}