Cod sursa(job #1212700)

Utilizator rockerboyHutter Vince rockerboy Data 25 iulie 2014 17:05:33
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <fstream>
#include <cstring>
#include <vector>

typedef class Trie
{
    int nr, wordend;
    Trie* next[26];

public:
    Trie();
    ~Trie();
    void insert(std::string::iterator, std::string::iterator);
    void erase(std::string::iterator, std::string::iterator);
    int appearances(std::string::iterator, std::string::iterator);
    int max_prefix_length(std::string::iterator, std::string::iterator);
};

Trie::Trie():nr(0), wordend(0)
{
    memset (next, NULL, 104);
}

Trie::~Trie()
{
    for (static int i=0; i<26; i++) {
        delete next[i];
    }
    memset (next, NULL, 104);
}

void Trie::insert(std::string::iterator begin, std::string::iterator end)
{
    if (begin < end) {
        if (!next[*begin-'a']) next[*begin-'a'] = new Trie;
        next[*begin-'a']->nr++;
        next[*begin-'a']->insert(begin+1, end);
    }
    else {
        wordend++;
    }
}

void Trie::erase(std::string::iterator begin, std::string::iterator end)
{
    if (begin < end) {
        next[*begin-'a']->nr--;
        next[*begin-'a']->erase(begin+1, end);
        if (!next[*begin-'a']->nr) {
            delete next[*begin-'a'];
            next[*begin-'a'] = NULL;
        }
    }
    else {
        wordend--;
    }
}

int Trie::appearances(std::string::iterator begin, std::string::iterator end)
{
    if (begin == end) return wordend;
    if (next[*begin-'a']) return next[*begin-'a']->appearances(begin+1, end);
    else return 0;
}

int Trie::max_prefix_length(std::string::iterator begin, std::string::iterator end)
{
    if (begin == end) return 0;
    if (next[*begin-'a']) return 1+next[*begin-'a']->max_prefix_length(begin+1, end);
    else return 0;
}

int main()
{
/********** Declarations **********/
    std::ifstream in ("Trie.in");
    std::ofstream out ("Trie.out");
    Trie MyTrie;
    int op;
    std::string current;
///==============================///

    while (in >> op >> current) {
        if (!op) MyTrie.insert(current.begin(), current.end());
        else if (op == 1) MyTrie.erase(current.begin(), current.end());
        else if (op == 2) out << MyTrie.appearances(current.begin(), current.end()) << "\n";
        else out << MyTrie.max_prefix_length(current.begin(), current.end()) << "\n";
    }

    return 0;
}