Cod sursa(job #3039626)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 28 martie 2023 18:37:48
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
///Buzatu Giulian
#include <bits/stdc++.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
int op;
string s;
class Trie
{
private:
    int apps,finish;///apps = appearances
    Trie* edge[26];
public:
    Trie(): apps(0), finish(0)
    {
        for(int i=0; i<26; i++)
            edge[i]=NULL;
    }
    void add(Trie* other,string& w);
    void clean(Trie* other,string& w,int pos);
    void no_apps(Trie* other,string& w);
    void prefix(Trie* other,string& w);
    ~Trie()
    {
        for(int i=0; i<26; i++)
            if(edge[i])
                delete edge[i];
    }
};
void Trie::add(Trie* p,string& w)
{
    for(int i=0; i<(int)w.size(); i++)
    {
        if(p->edge[w[i]-'a']==NULL)
            p->edge[w[i]-'a']=new Trie;
        p=p->edge[w[i]-'a'];
        p->apps++;
    }
    p->finish++;
}
void Trie::clean(Trie* p,string& w,int pos)
{
    if(pos<(int)w.size())
    {
        p->apps--;
        clean(p->edge[w[pos]-'a'],w,pos+1);
    }
    else
    {
        p->apps--;
        p->finish--;
        /*if(p->apps==0)
            delete p;*/
    }
}
void Trie::no_apps(Trie* p,string& w)
{
    int ans=-1;
    for(int i=0; i<(int)w.size(); i++)
    {
        if(p->edge[w[i]-'a']==NULL)
        {
            ans=0;
            break;
        }
        p=p->edge[w[i]-'a'];
    }
    if(ans==-1)
        ans=p->finish;
    g<<ans<<'\n';
}
void Trie::prefix(Trie* p,string& w)
{
    int ans=0;
    for(int i=0; i<(int)w.size(); i++)
    {
        if(p->edge[w[i]-'a']==NULL)
        {
            ans=i;
            break;
        }
        if(p->edge[w[i]-'a']->apps)
            p=p->edge[w[i]-'a'];
        else
        {
            ans=i;
            break;
        }
    }
    g<<ans<<'\n';
}
int main()
{
    Trie *head = new Trie;
    while(f>>op>>s)
    {
        if(op==0)
            head->add(head,s);
        else if(op==1)
            head->clean(head,s,0);
        else if(op==2)
            head->no_apps(head,s);
        else
            head->prefix(head,s);
    }
    delete head;
    return 0;
}