Cod sursa(job #2413844)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 23 aprilie 2019 19:10:29
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include <bits/stdc++.h>

using namespace std;

struct Trie
{
        int cnt;
        int CntKids;
        Trie *kids[26];
        Trie()
        {
                cnt=CntKids=0;
                for(int i=0;i<26;i++)
                {
                        kids[i]=0;
                }
        }
};

Trie *T=new Trie;

void Insert(Trie *nod,char *s)
{
        if(int(*s)==0)
        {
                nod->cnt++;
                return;
        }
        int Value=*s-'a';
        if(nod->kids[Value]==0)
        {
                nod->kids[Value]=new Trie;
                nod->CntKids++;
        }
        Insert(nod->kids[Value],s+1);
}

int Delete(Trie *nod,char *s)
{
        int Value=*s-'a';
        if(int(*s)==0)
        {
                nod->cnt--;
        }
        else
        {
                if(Delete(nod->kids[Value],s+1))
                {
                        nod->kids[Value]=0;
                        nod->CntKids--;
                }
        }
        if(nod->CntKids==0)
        {
                delete nod;
                return 1;
        }
        return 0;
}

int Solve(Trie *nod,char *s)
{
        if(int(*s)==0)
        {
                return nod->cnt;
        }
        int Value=*s-'a';
        if(nod->kids[Value])
        {
                return Solve(nod->kids[Value],s+1);
        }
        return 0;
}

int GetPrefix(Trie *nod,char *s,int Depth)
{
        int Value=*s-'a';
        if(int(*s)==0 || nod->kids[Value]==0)
        {
                return Depth;
        }
        return GetPrefix(nod->kids[Value],s+1,1+Depth);
}

int main()
{
        freopen("trie.in","r",stdin);
        freopen("trie.out","w",stdout);
        char s[100];
        while(cin.getline(s,100))
        {
                if(s[0]=='0') Insert(T,s+2);
                if(s[0]=='1') Delete(T,s+2);
                if(s[0]=='2') cout<<Solve(T,s+2)<<"\n";
                if(s[0]=='3') cout<<GetPrefix(T,s+2,0)<<"\n";
        }
        return 0;
}