Cod sursa(job #1450051)

Utilizator DrumeaVDrumea Vasile DrumeaV Data 11 iunie 2015 11:55:48
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <string.h>
using namespace std;

struct Trie
        {
            int Pref,Word;
            Trie *next[26];

            Trie()
            {
                Word = Pref = 0;
                memset(next,0,sizeof(next));
            }
        };

Trie *T = new Trie();

inline int Max(int A,int B)
{
    return (A > B) ? A : B;
}

void Ins(Trie *Node,char *S)
{
    Node->Pref++;
    if (*S == 0)
    {
        Node->Word++;
        return;
    }
    if (Node->next[*S - 'a'] == 0)
        Node->next[*S - 'a'] = new Trie();

    Ins(Node->next[*S - 'a'],S + 1);
}

void Del(Trie *Node,char *S)
{
    Node->Pref--;
    if (*S == 0)
    {
        Node->Word--;
        return;
    }
    Del(Node->next[*S - 'a'],S + 1);
}

int Cnt(Trie *Node,char *S)
{
    if (*S == 0)
        return Node->Word;

    if (Node->next[*S - 'a'] == 0)
        return 0;

    return Cnt(Node->next[*S - 'a'],S + 1);
}

int Prf(Trie *Node,char *S)
{
    if (Node->Pref == 0)
        return 0;

    if (*S == 0)
        return 1;

    if (Node->next[*S - 'a'] == 0)
        return 1;

    return 1 + Prf(Node->next[*S - 'a'],S + 1);
}

int main()
{
    char C[25];
    int Op;

    ifstream fin("trie.in");
    ofstream fout("trie.out");

    while (fin >> Op)
    {
        fin >> C;
        switch (Op)
        {
            case 0: Ins(T,C);break;
            case 1: Del(T,C);break;
            case 2: fout << Cnt(T,C) << '\n';break;
            case 3: fout << Max(0,Prf(T,C)-1) << '\n';break;
        }
    }
    return 0;
}