Cod sursa(job #1357914)

Utilizator NistorSergiuNistor Sergiu NistorSergiu Data 24 februarie 2015 10:42:57
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include <fstream>
#include <cstdio>
#include <cstring>

using namespace std;

struct TRIE
{
    int no_occurence;
    int no_sons;
    TRIE* next[26];

    TRIE()
    {
        no_occurence=0;
        no_sons=0;
        memset(next, 0, sizeof(next));
    }
};

char word[21];
TRIE* root=new TRIE;

void insert(TRIE *nod, char *str)
{
    if(*str=='\0')
        nod->no_occurence++;
    else
    {
        if(!nod->next[*str-'a'])
        {
            nod->next[*str-'a']=new TRIE;
            nod->no_sons++;
        }
        insert(nod->next[*str-'a'], str+1);
    }
}

bool remove(TRIE* nod, char *str)
{
    if(*str=='\0')
        nod->no_occurence--;
    else
    {
        if(remove(nod->next[*str-'a'], str+1))
        {
            nod->next[*str-'a']=0;
            nod->no_sons--;
        }
    }
    if(!nod->no_occurence && !nod->no_sons && nod!=root)
    {
        delete nod;
        return 1;
    }
    return 0;
}

/*void remove(TRIE* nod, char *str)
{
    if(*str=='\0')
        nod->no_occurence--;
    else
        remove(nod->next[*str-'a'], str+1);
}*/

int get_no_occurence(TRIE* nod, char *str)
{
    if(*str=='\0')
        return nod->no_occurence;
    if(nod->next[*str-'a'])
        return get_no_occurence(nod->next[*str-'a'], str+1);
    return 0;
}

int get_prefix_length(TRIE* nod, char* str, int len)
{
    if(*str=='\0' || !nod->next[*str-'a'])
        return len;
    return get_prefix_length(nod->next[*str-'a'], str+1, len+1);
}

int main()
{
    int option;
    ifstream f("trie.in");
    ofstream g("trie.out");
    while(f>>option)
    {
        f>>word;
        //if(word[0]=='\0' || word[0]=='\n')
        //    break;
        switch(option)
        {
            case 0: insert(root, word); break;
            case 1: remove(root, word); break;
            case 2: g<<get_no_occurence(root, word)<<"\n"; break;
            case 3: g<<get_prefix_length(root, word, 0)<<"\n"; break;
        }
    }
    f.close();
    g.close();
    return 0;
}