Cod sursa(job #2146944)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 28 februarie 2018 12:40:54
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.47 kb
#include <bits/stdc++.h>
#define SIGMA 26
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct TrieNode
{
    TrieNode *children[SIGMA];
    int nr_words,nr_children;
    TrieNode()
    {
        nr_words=0;
        nr_children=0;
        memset(children,NULL,sizeof(children));
    }
};
string s;
TrieNode *st[SIGMA];
TrieNode *root=new TrieNode;
int top;
TrieNode *found;
void insert_trie()
{
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        found=current_node->children[it-'a'];
        if(found)
            current_node=found;
        else
        {
            TrieNode *p=new TrieNode;
            current_node->children[it-'a']=p;
            current_node->nr_children++;
            current_node=p;
        }
    }
    current_node->nr_words++;
}
void delete_trie()
{
    top=0;
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        st[++top]=current_node;
        found=current_node->children[it-'a'];
        current_node=found;
    }
    string :: iterator it=s.end();
    --it;
    current_node->nr_words--;
    while(!(current_node->nr_words) and !(current_node->nr_children))
    {
        delete current_node;
        current_node=st[top--];
        current_node->children[*it-'a']=NULL;
        current_node->nr_children--;
        --it;
    }
}
int nr_appearances()
{
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        found=current_node->children[it-'a'];
        if(!found) return 0;
        current_node=found;
    }
    return current_node->nr_words;
}
int nr_prefixes()
{
    int ans=0;
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        found=current_node->children[it-'a'];
        if(!found) return ans;
        ans++;
        current_node=found;
    }
    return ans;
}
int main()
{
    int op;
    while(f>>op>>s)
    {
        switch (op)
        {
            case 0:
                {
                    insert_trie();
                    break;
                }
            case 1:
                {
                    delete_trie();
                    break;
                }
            case 2:
                {
                    g<<nr_appearances()<<'\n';
                    break;
                }
            case 3:
                {
                    g<<nr_prefixes()<<'\n';
                    break;
                }
        }
    }

    return 0;
}