Cod sursa(job #1295307)

Utilizator alexandru70Ungurianu Alexandru alexandru70 Data 19 decembrie 2014 10:25:56
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <fstream>
#include <vector>

using namespace std;

class TrieNode {

public:

    TrieNode() : TrieNode('\0') {}

    TrieNode(char symbol) :
        symbol(symbol),
        count(0),
        nrSons(0),
        toDelete(false),
        children(sigma) {}

    void insertWord(string::iterator c, string::iterator fn) {
        if(c!=fn) {
            if(!children[*c - 'a']) {
                children[*c - 'a'] = new TrieNode(*c - 'a');
                nrSons++;
            }
            children[*c - 'a']->insertWord(c+1,fn);
        }
        else
            count++;
    }

    void deleteWord(string::iterator c, string::iterator fn) {
        if(c!=fn) {
            if(children[*c - 'a']) {
                children[*c - 'a']->deleteWord(c+1,fn);
                if(children[*c - 'a']->toDelete) {
                    nrSons--;
                    delete children[*c - 'a'];
                    children[*c - 'a'] = nullptr;

                }
                if(nrSons == 0 && count == 0) {
                    toDelete = true;
                }
            }
        }
        else {
            count--;
            if(nrSons==0 && count==0) {
                toDelete = true;
            }
        }
    }

    unsigned findWord(string::iterator c, string::iterator fn) {
        if(c!=fn)
            if(children[*c - 'a'])
                return children[*c - 'a']->findWord(c+1,fn);
            else
                return 0;
        else {
            return count;
        }
    }
    unsigned longestPrefix(string::iterator c, string::iterator fn) {
        if(c!=fn && children[*c - 'a'])
                return 1 + children[*c - 'a']->longestPrefix(c+1,fn);
        return 0;
    }

private:
    static const unsigned sigma = 'z'-'a'+1;

    unsigned count;
    unsigned nrSons;
    char symbol;
    bool toDelete;

    vector<TrieNode *> children;
};


int main() {

    TrieNode trie;
    string s;
    unsigned type;
    ifstream in("trie.in");
    ofstream out("trie.out");
    while(in >> type >> s) {
        switch(type) {
            case 0: {
                trie.insertWord(s.begin(),s.end());
            }break;
            case 1: {
                trie.deleteWord(s.begin(),s.end());
            }break;
            case 2: {
                out << trie.findWord(s.begin(),s.end()) << '\n';
            }break;
            case 3: {
                out << trie.longestPrefix(s.begin(),s.end()) << '\n';
            }break;
        }
    }

    return 0;
}