Cod sursa(job #2756694)

Utilizator Botnaru_VictorBotnaru Victor Botnaru_Victor Data 2 iunie 2021 13:00:08
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>

using namespace std;

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


struct nod
{
    nod *next[26];
    int wC;
    int aC;
    nod()
    {
        for(int i=0;i<26;i++) next[i]=NULL;
        wC=0;
        aC=0;
    }
};

nod root;

void addRemove(bool removing,nod *n, string word, int p)
{
    int mod=removing?-1:1;

    n->aC+=mod;
    if(p==word.size()) {n->wC+=mod;return;}

    if(n->next[word[p]-'a']==NULL)
    {
        n->next[word[p]-'a']= new nod();
    }
    addRemove(removing,n->next[word[p]-'a'],word,p+1);
    if(n->next[word[p]-'a']->aC==0)
    {
        delete n->next[word[p]-'a'];
        n->next[word[p]-'a']=NULL;
    }

}

int queryPref(nod *n, string word, int p)
{
    if(p==word.size()) return p;
    if(n->next[word[p]-'a']!=NULL) return queryPref(n->next[word[p]-'a'],word,p+1);
    return p;
}

int queryWord(nod *n, string word,int p)
{
    if(p==word.size()) return n->wC;
    if(n->next[word[p]-'a']!=NULL) return queryWord(n->next[word[p]-'a'],word,p+1);
    return 0;
}


int main()
{
    int test;string word;
    while(fin>>test>>word)
    {
        switch(test)
        {
        case 2:
            fout<<queryWord(&root,word,0)<<'\n';
            break;
        case 3:
            fout<<queryPref(&root,word,0)<<'\n';
            break;
        default:
            addRemove(test==1,&root,word,0);
        }
    }
    return 0;
}