Cod sursa(job #2305635)

Utilizator Carol_LucaCarol Luca Carol_Luca Data 20 decembrie 2018 18:32:00
Problema Trie Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 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 i=0;

    nod=T;

    for(i=0;nod!=nullptr && i<=n;i++)

        nod=nod -> next[S[i]-'a'];

    fout<<i-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;

}