Cod sursa(job #1678328)

Utilizator BrandonChris Luntraru Brandon Data 7 aprilie 2016 10:53:21
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <fstream>
#include <cstring>

using namespace std;

ifstream cin("trie.in");
ofstream cout("trie.out");

int n;

class TrieNode {
  int cnt, subtree_words;
  TrieNode *Edg[26];

public:
  TrieNode(int _cnt = 0, int _subtree_words = 0) {
    cnt = _cnt;
    subtree_words = _subtree_words;
    memset(Edg, 0, sizeof Edg);
  }

  void TrieInsert(const string &str, const int &pos = 0) {
    if(str[pos] == 0) {
      ++cnt;
      ++subtree_words;
      return;
    }

    if(Edg[str[pos] - 'a'] == nullptr) { ///Word not in trie
      Edg[str[pos] - 'a'] = new TrieNode;
    }

    Edg[str[pos] - 'a']->TrieInsert(str, pos + 1);
    ++subtree_words;
  }

  void TrieRemove(const string &str, const int &pos = 0) {
    if(str[pos] == 0) {
      --cnt;
      --subtree_words;
      return;
    }

    Edg[str[pos] - 'a']->TrieRemove(str, pos + 1);
    --subtree_words;
  }

  int TrieAppr(const string &str, const int &pos = 0) {
    if(str[pos] == 0) { ///Word found
      return cnt;
    }

    if(Edg[str[pos] - 'a'] == nullptr) { ///Word not in Trie
      return 0;
    }

    return Edg[str[pos] - 'a']->TrieAppr(str, pos + 1);
  }

  int TriePrefix(const string &str, const int &pos = 0) {
    if(str[pos] == 0) {
      return pos;
    }

    if(subtree_words == 0) {
      return pos - 1;
    }

    if(Edg[str[pos] - 'a'] == nullptr) {
      return pos;
    }

    return Edg[str[pos] - 'a']->TriePrefix(str, pos + 1);
  }
};

TrieNode *Rt = new TrieNode;

int main() {
  int type;
  string str;

  while(cin >> type >> str) {
    if(type == 0) {
      Rt->TrieInsert(str);
    }
    else if(type == 1) {
      Rt->TrieRemove(str);
    }
    else if(type == 2) {
     cout << Rt->TrieAppr(str) << '\n';
    }
    else {
      cout << Rt->TriePrefix(str) << '\n';
    }
  }

  return 0;
}