Cod sursa(job #1597587)

Utilizator goalexboxerFMI Alexandru Ionascu goalexboxer Data 12 februarie 2016 09:18:45
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 2.23 kb
#include<bits/stdc++.h>
#define in f
#define out g
#define SIGMA 26
#define ascii (int)'a'
using namespace std;

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

class Trie {

    private:
    Trie* children[SIGMA];
    int value = 0;
    int count = 0;

    public:
    void insert(string word) {

        if(word.size() == 0) {
            this->count++;
            return;
        }

        if(children[word[0] - ascii] == NULL) {
            children[word[0] - ascii] = new Trie();
        }

        children[word[0] - ascii]->value++;
        children[word[0] - ascii]->insert(word.substr(1));
    }

    int find(string word) {
        if(word.size() == 0) {
            return this->count;
        }

        if(children[word[0] - ascii] == false || children[word[0] - ascii]->value == 0) {
            return 0;
        } else return children[word[0] - ascii]->find(word.substr(1));
    }

    void erase(string word) {
        if(word.size() == 0) {
            this->count--;
            return;
        }

        if(children[word[0] - ascii]) {
            children[word[0] - ascii]->value--;
            if(children[word[0] - ascii]->value == 0) {
                delete(children[word[0] - ascii]);
                return;
            } else children[word[0] - ascii]->erase(word.substr(1));
        }

    }

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

    int longestPrefix(string word, int length) {

        if(word.size() == 0) {
            return length;
        }

        if(children[word[0] - ascii] == false || children[word[0] - ascii]->value == 0) {
            return length;
        } else return children[word[0] - ascii]->longestPrefix(word.substr(1), length + 1);
    }

};

int main() {

    Trie* trie = new Trie();
    int operation;
    string word;

    while(in >> operation) {
        in >> word;

        switch(operation) {
            case 0:
                trie->insert(word);
                break;
            case 1:
                trie->erase(word);
                break;
            case 2:
                out << trie->find(word) << "\n";
                break;
            case 3:
                out << trie->longestPrefix(word) << "\n";
                break;
        }
    }

    return 0;
}