Cod sursa(job #1200468)

Utilizator mr.johnFMI - Laceanu Ionut-Adrian mr.john Data 22 iunie 2014 15:48:20
Problema Hashuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>

using namespace std;

struct node{
  int info;
  node* next;
  node(int i) {
    info = i;
    next = NULL;
  }
};

int h(int val) {
  return val % 666013;
}

int find(node* hash[], int val) {
  node* root = hash[h(val)];
  while(root) {
    if (root->info == val) return 1;
    root = root->next;
  }
  return 0;
}

int insert(node* hash[], int val) {
  if (find(hash, val)) {
    return 0;
  }
  node* nod = new node(val);
  nod->next = hash[h(val)];
  hash[h(val)] = nod;
  return 1;
}

int remove(node* hash[], int val) {
  node* root = hash[h(val)];
  if (!root) return 0;
  if (root->info == val) {
    hash[h(val)] = hash[h(val)]->next;
    delete root;
    return 1;
  }
  node* p1 = root->next;
  node* prev = root;
  while (p1) {
    if (p1->info == val) {
      prev->next = p1->next;
      return 1;
    }
    p1 = p1->next;
    prev = prev->next;
  }
  return 0;
}

// void clearNode(node* root) {
//   if (root == NULL) return;
//   clearNode(root->next);
//   free(root);
// }

// void clear(node* hash[]) {
//   for (int i = 0; i < 666013; i++) {
//     if (!hash[i]) continue;
//     delete hash[i];
//   }
// }

int main() {
  ifstream cin("hashuri.in");
  ofstream cout("hashuri.out");
  node* hash[666013];
  for(int i = 0; i < 666013; i++) {
    hash[i] = NULL;
  }
  int N;
  cin >> N;
  for (int i = 0; i < N; i++) {
    int op, x;
    cin >> op >> x;
    switch(op) {
      case 1:
        insert(hash, x);
        break;
      case 2:
        remove(hash, x);
        break;
      default:
        cout << find(hash, x) << '\n';
    }
  }
  return 0;
}