Cod sursa(job #2965447)

Utilizator Zed1YasuoAlex Birsan Zed1Yasuo Data 15 ianuarie 2023 13:04:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>

using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
int n,m,test;
struct Trie
{
    int nr,val;
    Trie *a[30];
    Trie()
    {
        val=nr=0;
        for(int i=0;i<29;i++)
            a[i]=0;
    }
};
Trie *T=new Trie;
void add(Trie *nod,string s,int poz,int n)
{
    if(poz==n)
    {
        nod->nr++;
        return;
    }
    int ch=s[poz]-'a';
    if(!nod->a[ch])
    {
        nod->val++;
        nod->a[ch]=new Trie;
    }
    add(nod->a[ch],s,poz+1,n);
}
bool stergere(Trie *nod, string s, int poz, int n)
{
    if(poz==n)
    {
        nod->nr--;
    }
    else
    {
        int ch=s[poz]-'a';
        if(stergere(nod->a[ch],s,poz+1,n))
        {
            nod->val--;
            nod->a[ch]=0;
        }
    }
    if(nod->val==0&&nod->nr==0&&nod!=T)
    {
        delete nod;
        return 1;
    }
    else
        return 0;
}
void tipar(Trie *nod,string s,int poz,int n)
{
    int ch=s[poz]-'a';
    if(poz==n)
    {
        g<<nod->nr<<'\n';
        return;
    }
    else
    if(!nod->a[ch])
    {
        g<<0<<'\n';
        return;
    }
    else
    {
        tipar(nod->a[ch],s,poz+1,n);
    }
}
void prefix(Trie *nod,string s, int poz,int n)
{
    int ch=s[poz]-'a';
    if(poz==n||!nod->a[ch])
    {
        g<<poz<<'\n';
        return ;
    }
    else
        prefix(nod->a[ch],s,poz+1,n);
}
int main()
{
    while(f>>test)
    {
        string s;
        f>>s;
        if(test == 0)
        {
            add(T,s,0,s.size());
        }
        else
        if(test== 1 )
            stergere(T,s,0,s.size());
        else
        if( test ==  2 )
            tipar(T,s,0,s.size());
        else
            prefix(T,s,0,s.size());
    }
    return 0;
}