Cod sursa(job #712075)

Utilizator psycho21rAbabab psycho21r Data 13 martie 2012 00:24:01
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
#include <fstream>
#include <string>
using namespace std;
class trie
{
    struct node
    {
        int n_sons, n_words;
        node *sons[26];
        node()
        {
            n_sons = n_words = 0;
            for(int i = 0; i < 26; ++i)
                sons[i] = NULL;
        }
    };
    node *root;
    public:
    trie()
    {
        root = new node;
    }
    void true_push(string str, node *here, int p)
    {
        if(p == str.size())
        {
            here->n_words++;
            return;
        }
        if(here->sons[str[p]-97] == NULL)
        {
            here->sons[str[p]-97] = new node;
            here->n_sons++;
        }
        true_push(str, here->sons[str[p]-97], p + 1);
    }
    void push(string str)
    {
        true_push(str, root, 0);
    }
    bool true_pop(string str, node *here, int p)
    {
        if(p == str.size())
            here->n_words--;
        else if(true_pop(str, here->sons[str[p]-97], p + 1))
        {
            here->sons[str[p]-97] = NULL;
            here->n_sons--;
        }
        if(here->n_words == 0 && here->n_sons == 0 && here!=NULL)
        {
            delete here;
            return true;
        }
        return false;
    }
    void pop(string str)
    {
        true_pop(str, root, 0);
    }
    int count(string str)
    {
        node *here = root;
        int i = 0;
        while(i < str.size())
        {
            if(here->sons[str[i]-97] == NULL)
                return 0;
            here = here -> sons[str[i]-97];
            ++i;
        }
        return here -> n_words;
    }
    int max_pref(string str)
    {
        int max = 0;
        node *here = root;
        int i = 0;
        while(i < str.size())
        {
            if(here -> sons[str[i]-97] == NULL)
                return max;
            here = here -> sons[str[i]-97];
            ++max;
            ++i;
        }
        return max;
    }
};
trie tr;
int main()
{
    int n;
    string str;
    ifstream in("trie.in");
    ofstream out("trie.out");
    while(in >> n >> str)
    {
        switch(n)
        {
            case 0: tr.push(str); break;
            case 1: tr.pop(str); break;
            case 2: out << tr.count(str) << "\n"; break;
            case 3: out << tr.max_pref(str) << "\n"; break;
        }
    }
    in.close();
    out.close();
    return 0;
}