Cod sursa(job #3188640)

Utilizator tudor_costinCostin Tudor tudor_costin Data 3 ianuarie 2024 16:44:56
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Trie{
    Trie *leg[26];
    int nrfii,fr;
    Trie()
    {
        for(int i=0;i<26;i++) leg[i]=0;
        nrfii=0,fr=0;
    }
};
Trie *rad=new Trie;
string s;
void Add(Trie *nod,int pos)
{
    if(pos==s.size())
    {
        nod->fr++;
        return;
    }
    int ch=s[pos]-'a';
    Trie *a=new Trie;
    if(!nod->leg[ch])
    {
        nod->leg[ch]=a;
        nod->nrfii++;
    }
    Add(nod->leg[ch],pos+1);
}
bool Delete(Trie *nod,int pos)
{
    if(pos==s.size())
    {
        nod->fr--;
    }
    else
    {
        int ch=s[pos]-'a';
        if(Delete(nod->leg[ch],pos+1))
        {
            nod->nrfii--;
            nod->leg[ch]=nullptr;
        }
    }
    if(nod->nrfii==0 && nod->fr==0 && nod!=rad)
    {
        delete nod;
        return true;
    }
    return false;
}
int Search(Trie *nod,int pos)
{
    if(pos==s.size())
    {
        return nod->fr;
    }
    int ch=s[pos]-'a';
    if(!nod->leg[ch])
    {
        return 0;
    }
    return Search(nod->leg[ch],pos+1);
}
int Lg(Trie *nod,int pos)
{
    int ch=s[pos]-'a';
    if(pos==s.size() || !nod->leg[ch])
    {
        return pos;
    }
    return Lg(nod->leg[ch],pos+1);
}
int main()
{
    int tip;
    bool ok;
    while(fin>>tip>>s)
    {
        if(tip==0) Add(rad,0);
        else
        {
            if(tip==1) ok=Delete(rad,0);
            else if(tip==2) fout<<Search(rad,0)<<'\n';
            else fout<<Lg(rad,0)<<'\n';
        }
    }
    return 0;
}