Cod sursa(job #1345281)

Utilizator hopingsteamMatraguna Mihai-Alexandru hopingsteam Data 17 februarie 2015 15:03:25
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include    <iostream>
#include    <fstream>
#include    <cstring>

using namespace std;

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

const int letters = 26;

struct Trie
{
    int Final, Sons;
    Trie *Son[letters];

    Trie()
    {
        Final = Sons = 0;
        memset(Son, 0, sizeof(Son));
    }
};

Trie *T = new Trie;

inline int ConvertChar(char *s)
{
    return *s - 'a';
}

/*void Chars(char linee[25])
{
    for(int i = 0; i < strlen(linee); i++)
    {
        cout << (int)linee[i] << " ";
    }
    cout << "\n";
}*/

void Insert(Trie *nod, char *s)
{
    if(*s == NULL)
        return;

    if(!(nod -> Son[ ConvertChar(s) ]))
    {
        nod -> Son[ ConvertChar(s) ] = new Trie;
        nod -> Sons += 1;
    }

    Insert(nod, s+1);
}

int Delete(Trie *nod, char *s)
{
    if(*s == NULL)
        nod -> Final -= 1;
    else
        if(Delete(nod -> Son[ ConvertChar(s) ], s + 1))
        {
            nod -> Son[ ConvertChar(s) ] = 0;
            nod -> Sons -= 1;
        }

    if(nod -> Final == 0 && nod -> Sons == 0 && nod != T)
    {
        delete nod;
        return 1;
    }
    return 0;
}

int Query(Trie *nod, char *s)
{
    if(*s == NULL)
        return nod -> Final;
    if(nod -> Son[ ConvertChar(s) ])
        return Query(nod -> Son[ ConvertChar(s) ], s+1);
    return 0;
}

int Prefix(Trie *nod, char *s, int k)
{
    if(*s == NULL || nod -> Son[ ConvertChar(s) ] == 0)
        return k;
    return Prefix( nod -> Son[ ConvertChar(s) ], s+1, k+1);
}

void Read()
{
    char line[25];

    while(fin.good())
    {
        fin.getline(line, 25);
        switch(line[0])
        {
            case '0':   Insert(T, line + 2); break;
            case '1':   Delete(T, line + 2); break;
            case '2':   fout << Query(T, line + 2); break;
            case '3':   fout << Prefix(T, line + 2, 0); break;
        }
    }

}

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