Cod sursa(job #2541231)

Utilizator RedXtreme45Catalin RedXtreme45 Data 8 februarie 2020 11:27:21
Problema Trie Scor 55
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.76 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");

struct  trie
{
    int ap;
    int val;
    trie *son[26];
    trie()
    {
        ap=0;
        val=0;
        memset(son,0,sizeof son);
    }
};
int main()
{
    int a;
    string s;
    trie *root=new trie;
    while (fin>>a>>s)
    {
        if (a==0)
        {
            trie *where=root;
            int i=0;
            int sz=s.size()-1;
            while (i<=sz)
            {
                if (where->son[s[i]-'a']==0)
                {
                    where->son[s[i]-'a']=new trie;
                    where->son[s[i]-'a']->ap++;
                    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;
            int i=0;
            int sz=s.size()-1;
            while (i<=sz)
            {
                where->son[s[i]-'a']->ap--;
                if (where->son[s[i]-'a']->ap==0)
                {
                    delete where->son[s[i]-'a'];
                    break;
                }
                if (i==sz)
                    where->son[s[i]-'a']->val--;
                where=where->son[s[i]-'a'];
                i++;
            }
        }
        if (a==2)
        {
            trie *where=root;
            int i=0;
            int sz=s.size()-1;
            int nr=0;
            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)
        {
            trie *where=root;
            int i=0;
            int sz=s.size()-1;
            int nr=0;
            while (i<=sz)
            {
                if (where->son[s[i]-'a']!=0)
            {

                if (where->son[s[i]-'a']->ap!=0)
                    {
                        nr++;
                        where=where->son[s[i]-'a'];
                        i++;
                    }
                    else
                        i=sz+1;
                }
                else
                    i=sz+1;

                }
            fout<<nr<<"\n";
        }
    }
    return 0;
}