Cod sursa(job #1700252)

Utilizator stoianmihailStoian Mihail stoianmihail Data 9 mai 2016 21:45:16
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <stdio.h>
#include <string.h>

#define SIGMA 26
#define Nadejde 25

struct trie {
  int count, numSons;
  trie *sons[SIGMA];

  trie() {
    this -> count = 0;
    this -> numSons = 0;
    memset(this -> sons, NULL, sizeof(this -> sons));
  }
};

char s[Nadejde];
#define next (s[ptr] - 'a')

trie *root = new trie;

void insert(trie *&nod, int ptr) {
  if (s[ptr] == '\n') {
    nod -> count++;
    return;
  }

  if (nod -> sons[next] == NULL) {
    nod -> sons[next] = new trie;
    nod -> numSons++;
  }
  insert(nod -> sons[next], ptr + 1);
}

int erase(trie *&nod, int ptr) {
  if (s[ptr] == '\n') {
    nod -> count--;
  } else if (erase(nod -> sons[next], ptr + 1)) {
    nod -> sons[next] = NULL;
    nod -> numSons--;
  }
  if (nod != root && nod -> count == 0 && nod -> numSons == 0) {
    delete nod;
    return 1;
  }
  return 0;
}

int find(trie *&nod, int ptr) {
  if (s[ptr] == '\n') {
    return nod -> count;
  }
  return nod -> sons[next] == NULL ? 0 : find(nod -> sons[next], ptr + 1);
}

int lcp(trie *&nod, int ptr, int len) {
  if (s[ptr] == '\n' || nod -> sons[next] == NULL) {
    return len;
  }
  return lcp(nod -> sons[next], ptr + 1, len + 1);
}

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

  while (fgets(s, Nadejde, f)) {
    switch (s[0]) {
      case '0':
        insert(root, 2);
        break;
      case '1':
        erase(root, 2);
        break;
      case '2':
        fprintf(stdout, "%d\n", find(root, 2));
        break;
      case '3':
        fprintf(stdout, "%d\n", lcp(root, 2, 0));
        break;
    }
  }
  fclose(f);
  fclose(stdout);

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