Cod sursa(job #2754961)

Utilizator xXoctavianXxStanescu Matei Octavian xXoctavianXx Data 26 mai 2021 18:19:39
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
# include <bits/stdc++.h>

using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Node
{
    Node *next[26];
    int word_count; //cuvinte care se termina aici
    int app_count; //aparitii in subarbore

    Node()   // constructorul pt Node (ce functie se apeleaza cand dam "new")
    {
        for (int i =0; i < 26; ++i)
        {
            next[i] = NULL;
        }
        word_count = 0;
        app_count = 0;
    }
};

string s;
int op;
Node *root;

void add_remove_word(bool is_removing, Node *current,string &word, int poz)  //pozitia in string
{
    int mod=is_removing?-1:1;
    current->app_count+=mod;
    if(poz==word.size())
    {
        current->word_count+=mod;
        return;
    }
    if(current->next[word[poz]-'a']==NULL)
    {
        current->next[word[poz]-'a']= new Node();
    }
    add_remove_word(is_removing, current->next[word[poz]-'a'], word, poz+1);

    if (current->next[word[poz]-'a']->app_count == 0)
    {
        delete current->next[word[poz]-'a'];
        current->next[word[poz]-'a']=NULL;
    }
}

int query_pref(Node *current, string &word, int poz)
{
    if(poz==word.size()) return word.size();


    if(current->next[word[poz]-'a']!=NULL)
        return query_pref(current->next[word[poz]-'a'], word, poz+1);
    return poz;

}

int word_count_query(Node *current, string &word, int poz)
{

    if(poz==word.size()) return current->word_count;
    if(current->next[word[poz]-'a']!=NULL)
        return word_count_query(current->next[word[poz]-'a'], word, poz+1);
    return 0;

}


int main()
{
    root=new Node();
    while(fin>>op>>s)
    {
        if(op==0||op==1) add_remove_word(op,root,s,0);
        else if(op==2) fout<<word_count_query(root,s,0)<<'\n';
        else fout<<query_pref(root,s,0)<<'\n';
    }
    return 0;
}