Cod sursa(job #2242135)

Utilizator alisavaAlin Sava alisava Data 17 septembrie 2018 21:00:22
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <bits/stdc++.h>
#define MaxChar 30


using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct Trie
{
    int val=0;
    int cuvant=0;
    Trie *next[MaxChar];
};
Trie *T;///Nodul initial
Trie *nod;///Nodul curent in parcurgere
int n; ///Lungimea cuvandtului
string S;

void Add()
{
    nod=T;
    for(int i=0;i<n;i++)
    {
        if(nod -> next[S[i]-'a'] == nullptr)
            nod -> next[S[i]-'a'] = new Trie;
        nod = nod ->next[S[i]-'a'];
        nod->val++;
        if ( i == n-1)
            nod -> cuvant++;
    }
}
void Del()
{
    Trie *pred; ///Tatal nodului nod
    nod=T;
    for(int i=0;i<n;i++)
    {
        pred=nod;
        nod = nod->next[S[i]-'a'];
        nod->val--;
        if(nod->val<=0)
        {
            pred->next[S[i]-'a']=nullptr;
            break;
        }
        if(i==n-1)
            nod->cuvant--;
    }
    nod=T;
}

void QueryNumber()
{
    nod=T;
    for(int i=0;i<n;i++)
    {
        nod = nod -> next[S[i]-'a'];
        if(nod==nullptr) break;
    }
    if(nod==nullptr)
        fout<<"0\n";
    else
        fout<<nod->cuvant<<"\n";
}
void QueryPrefix()
{
    int rez=0;
    nod=T;
    for(int i=0;nod!=nullptr && i<n;i++)
    {
        nod=nod -> next[S[i]-'a'];
        rez++;
    }
    fout<<rez-1<<"\n";
}




int main()
{
    int obt;
    T=new Trie;
    while(fin>>obt)
    {
        fin>>S;
        n=S.size();
        if(obt==0)
            Add();
        if(obt==1)
            Del();
        if(obt==2)
            QueryNumber();
        if(obt==3)
            QueryPrefix();


    }






    return 0;
}