Cod sursa(job #1243994)

Utilizator vlad.doruIon Vlad-Doru vlad.doru Data 16 octombrie 2014 17:38:35
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.92 kb
#include <iostream>
#include <fstream>
#include <memory>
#include <map>

using namespace std;

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

struct TrieNode{
  map<char, unique_ptr<TrieNode>> neighbours;
  int used_by;
  int final;
};

void AddWord(const string& word, const int& start, TrieNode* node) {
  if (start == word.size()) {
    node->final++;
    return;
  }
  if (node->neighbours[word[start]] == nullptr) {
    node->neighbours[word[start]].reset(new TrieNode());
  }
  node->neighbours[word[start]]->used_by++;
  AddWord(word, start + 1, node->neighbours[word[start]].get());
}

void RemoveWord(const string& word, const int& start, TrieNode* node) {
  if (start == word.size()) {
    node->final--;
    return;
  }
  if (node->neighbours[word[start]] == nullptr) {
    return;
  }
  if (--node->neighbours[word[start]]->used_by == 0) {
    node->neighbours[word[start]].reset();
    return;
  }
  RemoveWord(word, start + 1, node->neighbours[word[start]].get());
}

int CountWord(const string& word, const int& start, TrieNode* node) {
  if (start == word.size()) {
    return node->final;
  }
  if (node->neighbours[word[start]] == nullptr) {
    return 0;
  }
  return CountWord(word, start+1, node->neighbours[word[start]].get());
}

int LongestPrefix(const string& word, const int& start, TrieNode* node) {
  if (start == word.size()) {
    return 0;
  }
  if (node->neighbours[word[start]] != nullptr) {
    return 1 + LongestPrefix(word, start + 1,
                             node->neighbours[word[start]].get());
  }
  return 0;
}

int main (int argc, char const *argv[]) {
  int code;
  string word;
  TrieNode root;
  while(in>>code>>word) {
    if (code == 0) {
      AddWord(word, 0, &root);
    }
    if (code == 1) {
      RemoveWord(word, 0, &root);
    }
    if (code == 2) {
      out<< CountWord(word, 0, &root) << "\n";
    }
    if (code == 3) {
      out << LongestPrefix(word, 0, &root) << "\n";
    }
  }
  return 0;
}