Cod sursa(job #2258260)

Utilizator GiihuoTihufiNeacsu Stefan GiihuoTihufi Data 11 octombrie 2018 09:14:38
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <bits/stdc++.h>

using namespace std;

class trie
{
public:
    int cnt=0;
    string value="";
    map<char,trie> M;
    trie* parent;
    char ch='\0';
public:
    trie(){};
    void addCh(char c)
    {
        M[c].value=value+c;
        M[c].parent=this;
        M[c].ch=c;
    }
    void addWord(string s)
    {
        trie* _t=this;
        for(auto c:s)
        {
            _t->addCh(c);
            _t=&_t->M[c];
        }
        _t->cnt++;
    }

    bool findCh(char c)
    {
        return M.find(c)!=M.end();
    }

    int findWord(string s)
    {
        trie* _t=this;
        for(auto c:s)
        {
            if(!_t->findCh(c)) return 0;
            _t=&_t->M[c];
        }
        return _t->cnt;
    }

    int prefWord(string s)
    {
        int nr=0;
        trie* _t=this;
        for(auto c:s)
        {
            if(!_t->findCh(c)) break;
            nr++;
            _t=&_t->M[c];
        }
        return nr;
    }

    void delWord(string s)
    {
        trie* _t=this;
        for(auto c:s)
        {
            if(!_t->findCh(c)) return;
            _t=&_t->M[c];
        }
        _t->cnt--;
        while(_t->cnt==0 && _t->M.size()==0 && _t->parent!=NULL)
        {
            trie *c=_t->parent;
            (c->M).erase(_t->ch);
            _t=c;

        }
    }
    trie& operator [] (char c)
    {
        return M[c];
    }
};

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

int main()
{
    trie T;
    int n; string s;
    while(f>>n>>s)
    switch(n)
    {
        case 0:T.addWord(s);           break;
        case 1:T.delWord(s);           break;
        case 2:g<<T.findWord(s)<<'\n'; break;
        case 3:g<<T.prefWord(s)<<'\n'; break;
    }
    return 0;
}