Cod sursa(job #1415853)

Utilizator bciobanuBogdan Ciobanu bciobanu Data 6 aprilie 2015 17:50:50
Problema Hashuri Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <stdio.h>
#include <string.h>

#define MAX_N 1000000
#define MOD 666013
#define NIL -1

typedef struct {
  int v, next;
} hash;

hash l[MAX_N]; // liste simplu inlantuite alocate static
int lsize;
int h[MOD]; // inceputul listelor alocate static
int st[MAX_N], s; // stiva de pozitii refolosibile

inline int hashFind(int x) {
  int i = h[x - (x / MOD) * MOD];

  while ((i != NIL) && (l[i].v != x)) {
    i = l[i].next;
  }
  return i;
}
inline void hashInsert(int x) {
  int p = s ? st[s - 1] : lsize++;
  int hash = x - (x / MOD) * MOD;

  l[p].v = x;
  l[p].next = h[hash];
  h[hash] = p;
}
inline void hashExtract(int x) {
  int p = hashFind(x);

  if (p != NIL) {
    l[p].v = 0;
    st[s++] = p;
  }
}
int main(void) {
  FILE *f, *g;
  int testNum;
  int x;

  memset(h, NIL, MOD << 2);

  f = fopen("hashuri.in", "r");
  fscanf(f, "%d ", &testNum);
  g = fopen("hashuri.out", "w");
  for (; testNum; testNum--) {
    char c = fgetc(f);
    fscanf(f, "%d ", &x);
    switch (c) {
      case '1':
        hashInsert(x);
      break;
      case '2':
        hashExtract(x);
      break;
      case '3':
        fputc((hashFind(x) != NIL) + '0', g);
        fputc('\n', g);
      break;
    }
  }
  fclose(f);
  fclose(g);
  return 0;
}