Cod sursa(job #2403776)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 11 aprilie 2019 20:48:27
Problema Trie Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.43 kb
#include "vector"
#include "string"
#include "iostream"
#include "fstream"

using namespace std;

const int SIGMA = 30;

class Trie{
public:
  Trie(){
    _root = new Node;
    _root->value = 0;
    for(int i = 0; i < SIGMA; ++i){
      _root->edge[i] = nullptr;
    }
  }
  void Add(string word){
    _Add(word);
  }
  void Delete(string word){
    _Delete(word);
  }
  int GetCount(string word){
    return _GetCount(word);
  }
  int LongestPrefix(string word){
    return _LongestPrefix(word);
  }
private:
  void _Add(string word){
    Node *current_node = _root;
    for(int i = 0; i < word.size(); ++i){
      if(current_node->edge[word[i] - 'a'] == nullptr){
        Node *aux = new Node;
        aux->value = 0;
        for(int j = 0; j < SIGMA; ++j){
          aux->edge[j] = nullptr;
        }
        current_node->edge[word[i] - 'a'] = aux;
      }
      current_node = current_node->edge[word[i] - 'a'];
      current_node->prefix++;
    }
    current_node->value++;
  }
  void _Delete(string word){
    Node *current_node = _root;
    for(int i = 0; i < word.size(); ++i){
      current_node = current_node->edge[word[i] - 'a'];
      current_node->prefix--;
    }
    current_node->value--;
  }
  int _GetCount(string word){
    Node *current_node = _root;
    for(int i = 0; i < word.size(); ++i){
      if(current_node->edge[word[i] - 'a'] == nullptr){
        return 0;
      }
      current_node = current_node->edge[word[i] - 'a'];
    }
    return current_node->value;
  }
  int _LongestPrefix(string word){
    int lung = 0;
    Node *current_node = _root;
    for(int i = 0; i < word.size(); ++i){
      if(current_node->edge[word[i] - 'a'] == nullptr ||
        (current_node->edge[word[i] - 'a']->prefix <= 0)){
        return lung;
      }
      current_node = current_node->edge[word[i] - 'a'];
      if(current_node != _root){
        lung++;
      }
    }
    return lung;
  }
  struct Node{
    int value;
    int prefix;
    Node *edge[SIGMA];
  };
  Node *_root;

};
int main(){
  ifstream cin("trie.in");
  ofstream cout("trie.out");
  int x;
  Trie *trie = new Trie;
  while(cin >> x){
    string t;
    cin >> t;
    if(x == 0){
      trie->Add(t);
    }else if(x == 1){
      trie->Delete(t);
    }else if(x == 2){
      cout << trie->GetCount(t) << '\n';
    }else if(x == 3){
      cout << trie->LongestPrefix(t) << '\n';
    }
  }
  return 0;
}