Cod sursa(job #1946743)

Utilizator stefanchistefan chiper stefanchi Data 30 martie 2017 13:34:49
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <cstdio>
using namespace std;
int task;
char word[21];

struct TrieNode
{
    int WordAparition,ChildrenNumber;
    TrieNode* Children[27];
    TrieNode()
    {
        WordAparition = 0;
        ChildrenNumber = 0;
        for(int i = 0  ; i < 27 ; i++)
            Children[i] = NULL;
    }

}*root;

void InsertWord(TrieNode* &node, char *w)
{
    if(!*w)
    {
        node->WordAparition++;
        return;
    }
    if(node->Children[*w - 'a'] == 0)
    {
        node->Children[*w - 'a'] = new TrieNode;
        node->ChildrenNumber ++;
    }
    InsertWord(node->Children[*w - 'a'], w+1);
}

int DeleteWord(TrieNode* &node, char *w)
{
    if(!*w)
    {
        node->WordAparition--;
    }
    else if(DeleteWord(node->Children[*w - 'a'],w+1))
    {
        node->ChildrenNumber--;
        node->Children[*w - 'a'] = 0;
    }
    if( node->WordAparition == 0 && node->ChildrenNumber == 0 && node != root)
    {
        delete node;
        return 1;
    }
    return 0 ;
}

int GetAparition(TrieNode* & node, char * w)
{
    if(!*w)
    {
        return node->WordAparition;
    }
    if(node->Children[*w - 'a'])
        return GetAparition(node->Children[*w - 'a'],w+1);
    return 0;
}

int FindPrefix(TrieNode*&node, char* w, int lenght)
{
    if(!*w  ||  !node->Children[*w - 'a'])
        return lenght;
    else
        return  FindPrefix(node->Children[*w - 'a'],w+1,lenght+1);
}


void read()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    root = new TrieNode;
    while(scanf("%d %s",&task,word)== 2)
    {
        switch(task)
        {
        case 0 :
            InsertWord(root,word);
            break;
        case 1 :
            DeleteWord(root,word);
            break;
        case 2 :
            printf("%d",GetAparition(root,word));
            break;
        case 3 :
            printf("%d\n",FindPrefix(root,word,0));
            break;
        }
    }
}


int main()
{
    read();
    return 0;
}