Cod sursa(job #1217171)

Utilizator alex_HarryBabalau Alexandru alex_Harry Data 6 august 2014 19:57:30
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
#include <cstring>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct Trie{
int aparition,sons;
Trie* next[26];
    Trie()
    {
        aparition=sons=0;
        memset(next,0,sizeof(next));
    }
};
Trie* Root=new Trie;
char Str[50];
int findWord(char* s,Trie* node)
{
    if(*s=='\n')
        return node->aparition;
    if(node->next[(*s-'a')]!=0)
        return findWord(s+1,node->next[*s-'a']);
    return 0;
}

int longestPref(int level,char* s,Trie* node)
{
    if(*s=='\n' || node->next[*s-'a']==0)
        return level;
    return longestPref(level+1,s+1,node->next[*s-'a']);
}

void insert(Trie* node,char* s)
{
    if(*s=='\n')
    {
        node->aparition++;
        return;
    }
    if(node->next[*s-'a']==0)
    {
        node->next[*s-'a']=new Trie;
        node->sons++;
    }
    insert(node->next[*s-'a'],s+1);
}

bool deleteWord(Trie* node,char* s)
{
    if(*s=='\n')
        node->aparition--;
    else
        if(deleteWord(node->next[*s-'a'],s+1)==1)
        {
            node->next[*s-'a']=0;
            node->sons--;
        }
    if(node->aparition==0 && node->sons==0 && node!=Root)
    {
        delete node;
        return 1;
    }
    return 0;
}
int main()
{
    while(!f.eof())
    {
        f.getline(Str,35);
        int length=strlen(Str);
        Str[length]='\n';
        switch(Str[0])
        {
            case '0':insert(Root,Str+2);break;
            case '1':deleteWord(Root,Str+2);break;
            case '2':g<<findWord(Str+2,Root)<<"\n";break;
            case '3':g<<longestPref(0,Str+2,Root)<<"\n";break;
        }
        memset(Str,0,sizeof(Str));
    }
    return 0;
}