Cod sursa(job #1711414)

Utilizator stoianmihailStoian Mihail stoianmihail Data 31 mai 2016 09:49:37
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAGIC 13

struct node {
  int key;
  node *next;
};

class table {
  private:
  int MOD;
  node **adj;

  public:
  table() {
    MOD = rand() % 32 + MAGIC;
    adj = new node* [MOD];
  }

  private:
  int find(int h, int x) {
    node *curr = adj[h];
    while (curr != NULL && curr -> key != x) {
      curr = curr -> next;
    }
    return curr != NULL;
  }

  public:
  void insert(int x) {
    int h = x % MOD;
    if (find(h, x)) {
      return;
    }
    node *curr = new node;
    curr -> key = x;
    curr -> next = adj[h];
    adj[h] = curr;
  }

  void erase(int x) {
    int h = x % MOD;
    if (adj[h] == NULL) {
      return;    
    }
    if (adj[h] -> key == x) {
      adj[h] = adj[h] -> next;
      return;
    }
    node *prev = adj[h];
    node *curr = prev -> next;
    while (curr != NULL && curr -> key != x) {
      prev = curr;
      curr = curr -> next;
    }
    if (curr != NULL) {
      prev -> next = curr -> next;
    }
  }

  bool search(int x) {
    return find(x % MOD, x);
  }
};

#define MOD 131071

int N, h;
table hash[MOD + 1];

void insert(int x) {
  hash[x & MOD].insert(x);
}

void erase(int x) {
  hash[x & MOD].erase(x);
}

int find(int x) {
  return hash[x & MOD].search(x);
}

int main(void) {
  int task, x;
  FILE *f = fopen("hashuri.in", "r");
  freopen("hashuri.out", "w", stdout);

  srand(time(NULL));

  fscanf(f, "%d", &N);
  while (N) {
    fscanf(f, "%d %d", &task, &x);
    switch (task) {
      case 1:
        insert(x);
        break;
      case 2:
        erase(x);
        break;
      case 3:
        fprintf(stdout, "%d\n", find(x));
    }
    N--;
  }
  fclose(f);
  fclose(stdout);

  /// Multumim Doamne!
  puts("Doamne ajuta!");
  return 0;
}