Cod sursa(job #1356916)

Utilizator NistorSergiuNistor Sergiu NistorSergiu Data 23 februarie 2015 17:32:35
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 2.48 kb
#include <fstream>
#include <cstring>
using namespace std;
struct NOD
{
    int nr_words;
    struct :: NOD* next[26];
};
NOD zero;
NOD root;
int len_word;
char word[21];
void add(NOD& nod, int pos)
{
    if(pos==len_word)
    {
        if(nod.next[word[pos]-'a'])
            nod.next[word[pos]-'a']->nr_words++;
        else
        {
            NOD* new_nod;
            new_nod=new NOD;
            *new_nod=zero;
            new_nod->nr_words=1;
            nod.next[word[pos]-'a']=new_nod;
        }
    }
    else
    {
        if(!nod.next[word[pos]-'a'])
        {
            NOD* new_nod;
            new_nod=new NOD;
            *new_nod=zero;
            nod.next[word[pos]-'a']=new_nod;
        }
        add(*nod.next[word[pos]-'a'], pos+1);
    }
}
void remove(NOD& nod, int pos)
{
    if(pos==len_word)
    {
        nod.next[word[pos]-'a']->nr_words--;
    }
    else
    {
        //if(nod.next[word[pos]-'a'])
           // nod=*nod.next[word[pos]-'a'];
        /*else
        {
            NOD* new_nod;
            new_nod=new NOD;
            *new_nod=zero;
            nod.next[word[pos]-'a']=new_nod;
            nod=*new_nod;
        }*/
        remove(*nod.next[word[pos]-'a'], pos+1);
    }
}
int number_of_occurences(NOD& nod, int pos)
{
    if(pos==len_word)
    {
        if(nod.next[word[pos]-'a'])
            return nod.next[word[pos]-'a']->nr_words;
        else
            return 0;
    }
    else
    {
        if(nod.next[word[pos]-'a'])
            return number_of_occurences(*nod.next[word[pos]-'a'], pos+1);
        else
            return 0;
    }
}
int max_length_of_prefix(NOD& nod, int pos)
{
    if(pos>len_word)
    {
        return pos;
    }
    else
    {
        if(nod.next[word[pos]-'a'])
            return max_length_of_prefix(*nod.next[word[pos]-'a'], pos+1);
        else
        {
            return pos;
        }

    }
}
int main()
{
    int operation;
    root=zero;
    ifstream f("trie.in");
    ofstream g("trie.out");
    while(f>>operation)
    {
        f>>word;
        len_word=strlen(word)-1;
        switch(operation)
        {
            case 0: add(root, 0); break;
            case 1: remove(root, 0); break;
            case 2: g<<number_of_occurences(root, 0)<<'\n'; break;
            case 3: g<<max_length_of_prefix(root, 0)<<'\n'; break;
            //case 3: g<<number_of_occurences(root, 0)<<'\n'; break;
        }
    }
    return 0;
}