Cod sursa(job #2285487)

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

using namespace std;

const int ASIZE = 26;

class TrieNode {
public:
   TrieNode() {
      app = 0;
      ccnt = 0;
      for (int i = 0; i < ASIZE; ++i) {
         next[i] = nullptr;
      }
   }
   TrieNode* next[ASIZE];
   int app;
   int ccnt;
};

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

   void add_word(const 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_(const 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(const string& w) {
      delete_(w, root);
   }

   int get_word(const 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(const 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];
         }
      }

      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;
}