Cod sursa(job #2572270)

Utilizator RedXtreme45Catalin RedXtreme45 Data 5 martie 2020 12:21:53
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.75 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie
{
    int ap,val;
    trie *son[26];
    trie ()
    {
        ap=0;
        val=0;
        memset(son,0,sizeof son);
    }
};
trie *root=new trie;
int a,l;
string s;
bool del(trie *where,int poz)
{
    if (poz==l)
    {
        where->val--;
    }
    else
    {
        if (del(where->son[s[poz]-'a'],poz+1))
        {
            where->son[s[poz]-'a']=0;
        }
    }
    where->ap--;
    if (where->ap==0 && where!=root)
    {
        delete where;
        return 1;
    }
    return 0;
}
int main()
{
    while (fin>>a>>s)
    {
        if (a==0)
        {
             int sz=s.size()-1;
            int i=0;
            trie *where=root;
            while (i<=sz)
            {
                if (where->son[s[i]-'a']==0)
                {
                    where->son[s[i]-'a']=new trie;
                    where->son[s[i]-'a']->ap=1;
                    if (i==sz)
                        where->son[s[i]-'a']->val++;
                }
                else
                {
                    where->son[s[i]-'a']->ap++;
                    if (i==sz)
                        where->son[s[i]-'a']->val++;
                }
                where=where->son[s[i]-'a'];
                i++;
            }
        }
        if (a==1)
        {
            trie *where=root;
            l=s.size();;
            del(where,0);
        }
        if (a==2)
        {
            int i=0;
            int nr=0;
            trie *where=root;
            int sz=s.size()-1;
            while (i<=sz)
            {
                if (where->son[s[i]-'a']==0)
                {
                    i=sz+1;
                }
                else
                {
                    if (i==sz)
                        nr=where->son[s[i]-'a']->val;
                    where=where->son[s[i]-'a'];
                }
                i++;
            }
            fout<<nr<<"\n";
        }
        if (a==3)
        {
            int i=0;
            int nr=0;
            trie *where=root;
            int sz=s.size()-1;
            while (i<=sz)
            {
                if (where->son[s[i]-'a']==0)
                {
                    i=sz+1;
                }
                else
                {
                    if (where->son[s[i]-'a']->ap==0)
                        i=sz+1;
                    else
                    {
                        nr++;
                        where=where->son[s[i]-'a'];
                    }
                }
                i++;
            }
            fout<<nr<<"\n";
        }
    }
    return 0;
}