Cod sursa(job #2757217)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 4 iunie 2021 16:08:33
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <cstdio>
#include <memory.h>
using namespace std;

class Trie{
public:
  Trie() {
    memset(children, 0, sizeof(children));
    childrenCount = 0;
    wordCount = 0;
  }
  void Add(char *p) {
    if (*p == 0) {
      ++wordCount;
      return;
    }
    if (children[getIndex(p)] == 0) {
      children[getIndex(p)] = new Trie();
      ++childrenCount;
    }
    children[getIndex(p)]->Add(p + 1);  
  }
  int Count(char *p) {
    if (*p == 0) {
      return wordCount;
    }
    if (children[getIndex(p)] == 0)
      return 0;
    return children[getIndex(p)]->Count(p+1);    
  }
  int Prefix(char *p) {
    if (*p == 0 || children[getIndex(p)] == 0) {
      return 0;
    }
    return 1 + children[getIndex(p)]->Prefix(p + 1);
  }
  void Delete(char *p) {
    if (*p == 0) {
     --wordCount;
     return;
    }

    children[getIndex(p)]->Delete(p+1);

    if (children[getIndex(p)]->wordCount == 0 &&
	children[getIndex(p)]->childrenCount == 0) {
      delete children[getIndex(p)];
      children[getIndex(p)] = 0;
    }								   
    
  }
private:
  int getIndex(char *p) {
    return *p - 'a';
  }
  Trie *children[26];
  int childrenCount;
  int wordCount;
};

int main()
{
  freopen("trie.in", "r", stdin);
  freopen("trie.out", "w", stdout);

  int op;
  char word[30];

  Trie T;

  while (scanf("%d%s", &op, word) == 2) {
    if (op == 0)
      T.Add(word);
    if (op == 1)
      T.Delete(word);
    if (op == 2)
      printf("%d\n", T.Count(word));
    if (op == 3)
      printf("%d\n", T.Prefix(word));
  }
  
  return 0;
}