Cod sursa(job #2405261)

Utilizator alexalghisiAlghisi Alessandro Paolo alexalghisi Data 14 aprilie 2019 11:25:38
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>

const int SIGMA = 26;

int ch(const char& c) {
  return c - 'a';
}

struct Trie {
  int ends;
  int frecv;
  Trie* son[SIGMA];
  Trie() {
    ends = 0;
    frecv = 0;
    for (int i = 0; i < SIGMA; i++)
      son[i] = NULL;
  }
};

Trie *T = new Trie;

Trie* insertTrie(Trie *T, char *s) {
  if (T == NULL)
    T = new Trie;
  T->frecv++;
  if (s[0] == '\0') {
    T->ends++;
  } else {
    int c = ch(s[0]);
    T->son[c] = insertTrie(T->son[c], s + 1);
  }
  return T;
}

Trie* deleteTrie(Trie *T, char *s) {
  T->frecv--;
  if (s[0] == '\0') {
    T->ends--;
  } else {
    int c = ch(s[0]);
    T->son[c] = deleteTrie(T->son[c], s + 1);
  }
  if (T->frecv == 0)
    T = NULL;
  return T;
}

int getFrecv(Trie *T, char *s) {
  if (T == NULL)
    return 0;
  if (s[0] == '\0')
    return T->ends;
  return getFrecv(T->son[ch(s[0])], s + 1);
}

int maxPref(Trie *T, char *s) {
  if (T == NULL)
    return -1;
  if (s[0] == '\0')
    return 0;
  int c = ch(s[0]);
  return 1 + maxPref(T->son[c], s + 1);
}

int main() {

  std::ifstream fin("trie.in");
  std::ofstream fout("trie.out");

  int tip;
  while (fin >> tip) {
    char s[2 + 100];
    fin >> s;
    if (tip == 0) {
      T = insertTrie(T, s);
    } else if (tip == 1) {
      T = deleteTrie(T, s);
    } else if (tip == 2) {
      fout << getFrecv(T, s) << '\n';
    } else if (tip == 3) {
      fout << maxPref(T, s) << '\n';
    }
  }

  return 0;
}