Cod sursa(job #2146921)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 28 februarie 2018 12:32:18
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.55 kb
#include <bits/stdc++.h>
#define SIGMA 26
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct TrieNode
{
    map <char,TrieNode*> children;
    int nr_words;
    TrieNode() {nr_words=0;}
};
string s;
TrieNode *st[SIGMA];
TrieNode *root=new TrieNode;
int top;
map <char,TrieNode*> :: iterator found;
void insert_trie()
{
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        found=current_node->children.find(it);
        if(found!=current_node->children.end())
            current_node=found->second;
        else
        {
            TrieNode *p=new TrieNode;
            current_node->children.insert(pair <char,TrieNode*> (it,p));
            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.find(it);
        current_node=found->second;
    }
    string :: iterator it=s.end();
    --it;
    current_node->nr_words--;
    while(!(current_node->nr_words) and current_node->children.empty())
    {
        delete current_node;
        current_node=st[top--];
        current_node->children.erase(current_node->children.find(*it));
        --it;
    }
}
int nr_appearances()
{
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        found=current_node->children.find(it);
        if(found==current_node->children.end()) return 0;
        current_node=found->second;
    }
    return current_node->nr_words;
}
int nr_prefixes()
{
    int ans=0;
    TrieNode *current_node=root;
    for(const auto &it:s)
    {
        found=current_node->children.find(it);
        if(found==current_node->children.end()) return ans;
        ans++;
        current_node=found->second;
    }
    return ans;
}
int main()
{
    root->children.insert(pair <char,TrieNode*> ('?',NULL));
    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;
}