Cod sursa(job #2285480)

Utilizator ZappaManIosif Adrian-Mihai ZappaMan Data 18 noiembrie 2018 17:17:55
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.44 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

const int ASIZE = 30;

class TrieNode {
public:
   TrieNode() {
      app = 0;
      ccnt = 0;
      next = vector<TrieNode*>(ASIZE, nullptr);
   }
   vector<TrieNode*> next;
   int app;
   int ccnt;
};

class Trie {
public:
   Trie() {
      root = new TrieNode();
   }

   void add_word(string w) {
      TrieNode *node = root;

      for (char c : w) {
         int ix = int(c - 'a');
         if (node->next[ix] == nullptr) {
            TrieNode* new_node = new TrieNode();
            node->next[ix] = new_node;
            node->ccnt++;

            node = new_node;
         } else {
            node = node->next[ix];
         }
      }

      node->app += 1;
   }

   int delete_(string w, TrieNode* node) {
      if (w.size() == 0) {
         node->app--;
      } else {
         int ix = int(w[0] - 'a');
         if (node->next[ix] != nullptr) {
            if (delete_(w.substr(1), node->next[ix])) {
               node->ccnt--;
               node->next[ix] = nullptr;
            }
         }
      }

      if (node->app == 0 && node->ccnt == 0) {
         delete node;
         return 1;
      }

      return 0;
   }

   void delete_word(string w) {
      delete_(w, root);
   }

   int get_word(string w) {
      TrieNode *node = root;

      for (char c : w) {
         int ix = int(c - 'a');
         if (node->next[ix] == nullptr) {
            return 0;
         } else {
            node = node->next[ix];
         }
      }

      return node->app;
   }

   int get_longest(string w) {
      TrieNode *node = root;

      int longest_pref = 0;
      for (char c : w) {
         int ix = int(c - 'a');
         if (node->next[ix] == nullptr) {
            return longest_pref;
         } else {
            longest_pref += 1;
            node = node->next[ix];
         }
      }

      // check if there is a word
      return longest_pref;
   }


   TrieNode* root = nullptr;
};


int main() {
   ifstream iff("trie.in");
   ofstream off("trie.out");

   Trie t;
   int type;
   string word;

   while (iff >> type >> word) {
      switch (type) {
         case 0:
            t.add_word(word);
            break;
         case 1:
            t.delete_word(word);
            break;
         case 2:
            off << t.get_word(word) << endl;
            break;
         case 3:
            off << t.get_longest(word) << endl;
            break;
      }
   }

   return 0;
}