Cod sursa(job #1049802)

Utilizator andra23Laura Draghici andra23 Data 7 decembrie 2013 20:06:32
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class TrieNode {
  public:
  int wordNum, childrenNum;
  TrieNode* children[26];

  TrieNode() {
    wordNum = 0;
    childrenNum = 0;
    for (int i = 0; i < 26; i++) {
      children[i] = NULL;
    }
  }
};

class Trie {
  TrieNode* root;

  void addWord(TrieNode* node, const string& word, int pos) {
    if (pos == word.size()) {
      node->wordNum++;
    } else {
      int child = word[pos]-'a';
      if (node->children[child] == NULL) {
        node->children[child] = new TrieNode();
        node->childrenNum++;
      }
      addWord(node->children[child], word, pos+1);
    }
  }

  bool deleteWord(TrieNode* node, const string& word, int pos) {
    if (pos == word.size()) {
      if (node->wordNum > 0) {
        node->wordNum--;
      }
    } else {
      int child = word[pos]-'a';
      if (node->children[child] != NULL) {
        if (deleteWord(node->children[child], word, pos+1)) {
          node->children[child] = NULL;
          node->childrenNum--;
        }
      }
    }
    if (node->wordNum == 0 && node->childrenNum == 0 && node != root) {
      delete node;
      return true;
    } else {
      return false;
    }
  }

  int count(TrieNode* node, const string& word, int pos) {
    if (pos == word.size()) {
      return node->wordNum;
    } else {
      int child = word[pos]-'a';
      if (node->children[child] == NULL) {
        return 0;
      } else {
        return count(node->children[child], word, pos+1);
      }
    }
  }

  int longestPrefix(TrieNode* node, const string& word, int pos) {
    if (pos == word.size()) {
      return pos;
    } else {
      int child = word[pos]-'a';
      if (node->children[child] == NULL) {
        return pos;
      } else {
        return longestPrefix(node->children[child], word, pos+1);
      }
    }
  }

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

  void addWord(const string& word) {
    addWord(root, word, 0);
  }

  void deleteWord(const string& word) {
    deleteWord(root, word, 0);
  }

  int count(const string& word) {
    return count(root, word, 0);
  }

  int longestPrefix(const string& word) {
    return longestPrefix(root, word, 0);
  }
};

int main() {
  ifstream f("trie.in");
  ofstream g("trie.out");

  Trie trie;

  while (true) {
    int operationType;
    f >> operationType;
    if (f.eof()) {
      break;
    }
    f.get();
    string word;
    getline(f, word);
    if (operationType == 0) {
      trie.addWord(word);
    } else if (operationType == 1) {
      trie.deleteWord(word);
    } else if (operationType == 2) {
      g << trie.count(word) << '\n';
    } else {
      g << trie.longestPrefix(word) << '\n';
    }
  }

  return 0;
}