Cod sursa(job #1976994)

Utilizator blatulInstitutul de Arta Gastronomica blatul Data 4 mai 2017 19:18:56
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <bits/stdc++.h>
using namespace std;

#define ALFA 26

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

class Trie;

class TrieNode {

public:

    int visited;
    int finish;

    TrieNode* alfa[ALFA];

    TrieNode() {

        this->visited = 0;
        this->finish = 0;

        for (int i = 0; i < ALFA; ++i)
            this->alfa[i] = nullptr;
    }


    friend Trie;
};

class Trie {

public:

    TrieNode* root;

    Trie() {

        root = new TrieNode();
    }

    void insertWord(TrieNode*& node, const string& word, int idx) {

        node->visited++;

        if (idx >= word.length()) {
            node->finish++;
            return;
        }

        if (!node->alfa[word[idx] - 'a'])
            node->alfa[word[idx] - 'a'] = new TrieNode();

        this->insertWord(node->alfa[word[idx] - 'a'], word, idx + 1);
    }

    void eraseWord(TrieNode*& node, const string& word, int idx) {

        node->visited--;

        if (idx >= word.length()) {
            node->finish--;
            return;
        }

        this->eraseWord(node->alfa[word[idx] - 'a'], word, idx + 1);
    }

    int countAparition(TrieNode*& node, const string& word, int idx) {

        if (idx >= word.length()) {
            return node->finish;
        }

        if (!node->alfa[word[idx] - 'a'])
            return 0;

        return this->countAparition(node->alfa[word[idx] - 'a'], word, idx + 1);
    }

    int getLongestPref(TrieNode* node, const string& word) {

        int i;
        for (i = 0; i < word.length(); ++i) {

            if (!node->alfa[word[i] - 'a'])
                return i;

            node = node->alfa[word[i] - 'a'];

            if (node->visited < 1)
                return i;
        }

        return i;
    }
};

int main() {

    int t;
    string word;

    Trie* myTrie = new Trie();

    while (fin >> t >> word) {

        if (t == 0) {
            myTrie->insertWord(myTrie->root, word, 0);
        }
        else if (t == 1) {
            myTrie->eraseWord(myTrie->root, word, 0);
        }
        else if (t == 2) {
            fout << myTrie->countAparition(myTrie->root, word, 0) << "\n";
        }
        else if (t == 3) {
            fout << myTrie->getLongestPref(myTrie->root, word) << "\n";
        }
    }

    return 0;
}