Cod sursa(job #996508)

Utilizator BeilandArnoldArnold Beiland BeilandArnold Data 12 septembrie 2013 10:22:03
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <string>
using std::string;

class TRIE{
    private:
        unsigned nrwords;
        unsigned nrprefix;
        TRIE *p[26];
    public:
        TRIE(){ nrwords=0; nrprefix=0; for(unsigned i=0;i<26;++i) p[i]=0;}
        ~TRIE(){ for(unsigned i=0;i<26;++i) if(p[i]!=0) delete p[i]; }
        void add(const char *s){
            if(*s=='\0') ++nrwords;
            else{
                ++nrprefix;
                if(p[*s-'a']==0) p[*s-'a']=new TRIE;
                p[*s-'a']->add(s+1);
            }

        }
        bool rm(const char *s){
            if(*s=='\0'){
                --nrwords;
                if(nrprefix+nrwords==0) return true;
                else return false;
            }
            else{
                --nrprefix;
                bool b=p[*s-'a']->rm(s+1);
                if(b){
                    delete p[*s-'a'];
                    p[*s-'a']=0;
                }
                if(nrprefix+nrwords==0) return true;
                else return false;
            }
        }
        unsigned nrap(const char *s){
            if(*s=='\0') return nrwords;
            else if(p[*s-'a']) return p[*s-'a']->nrap(s+1);
            else return 0;
        }
        unsigned lmaxpref(const char *s){
            if(*s=='\0') return 0;
            else if(p[*s-'a']==0) return 0;
            else return 1+p[*s-'a']->lmaxpref(s+1);
        }
};


int main(){
    std::ifstream fin("trie.in");
    std::ofstream fout("trie.out");

    TRIE mtrie;

    char c; string w;
    for(;;){
        fin>>c>>w;
        if(fin.eof()) break;
        switch(c){
            case '0':
                mtrie.add(w.c_str());
                break;
            case '1':
                mtrie.rm(w.c_str());
                break;
            case '2':
                fout<<mtrie.nrap(w.c_str())<<'\n';
                break;
            case '3':
                fout<<mtrie.lmaxpref(w.c_str())<<'\n';
                break;
        }
    }

}