Cod sursa(job #1155455)

Utilizator alexandru70Ungurianu Alexandru alexandru70 Data 26 martie 2014 22:10:22
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>

using namespace std;

struct TrieNode {
    unsigned cnt,nrSons;
    bool toDelete;
    TrieNode *chd['z'-'a'+1];

    TrieNode() {
        cnt = nrSons = 0;
        toDelete = false;
        for(size_t i = 0; i < 'z'-'a'+1; ++i)
            chd[i] = nullptr;
    }
    void insertWord(string s) {
        if(s.size()>0) {
            if(!chd[s[0]-'a']) {
                chd[s[0]-'a'] = new TrieNode;
                nrSons++;
            }
            chd[s[0]-'a']->insertWord(s.substr(1,string::npos));
        }
        else
            cnt++;
    }

    void deleteWord(string s) {
        if(s.size() > 0) {
            if(chd[s[0]-'a']) {
                chd[s[0]-'a']->deleteWord(s.substr(1,string::npos));
                if(chd[s[0]-'a']->toDelete) {
                    nrSons--;
                    delete chd[s[0]-'a'];
                }
                if(nrSons == 0 && cnt == 0) {
                    toDelete = true;
                }
            }
        }
        else {
            cnt--;
            if(nrSons==0 && cnt==0) {
                toDelete = true;
            }
        }
    }

    unsigned findWord(string s) {
        if(s.size()>0)
            if(chd[s[0]-'a'])
                return chd[s[0]-'a']->findWord(s.substr(1,string::npos));
            else
                return 0;
        else {
            return cnt;
        }
    }
    unsigned longestPrefix(string s) {
        if(s.size()>0) {
            if(nrSons > 1) {
                return 0;
            }
            else {
                return 1 + chd[s[0]-'a']->longestPrefix(s.substr(1,string::npos));
            }
        }
        return 0;
    }
};


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);
            }break;
            case 1: {
                trie.deleteWord(s);
            }break;
            case 2: {
                out << trie.findWord(s) << '\n';
            }break;
            case 3: {
                out << trie.longestPrefix(s) << '\n';
            }break;
        }
    }

    return 0;
}