Cod sursa(job #1412956)

Utilizator gapdanPopescu George gapdan Data 1 aprilie 2015 17:49:21
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#define NMAX 100

using namespace std;

int t;
char s[30];
struct trie
{
    int nr1,nr2;
    trie *nod[26];
    trie()
    {
        nr1=nr2=0;
       for(int i = 0; i < 26; ++i) nod[i] = 0;
    }
}*root;

void add(trie *rad, char *s)
{
    if (*s == 0)
    {
        rad->nr1++;
        return;
    }
    if (rad->nod[*s-'a'] == NULL)
    {
        rad->nod[*s - 'a'] = new trie;
        rad->nr2++;
    }
    add(rad->nod[*s-'a'],s+1);
}

bool sterge(trie *&rad,char *s)
{
    if (*s == 0)
    {
        rad->nr1--;
        if (rad -> nr1 == 0 && rad -> nr2 == 0 && rad != root)
        {
            rad = NULL;
            return 1;
        }
        return 0;
    }
    if (sterge(rad->nod[*s-'a'],s+1))
    {
        rad -> nr2--;
        if (rad -> nr1 == 0 && rad -> nr2 == 0 && rad != root)
        {
            rad = NULL;
            return 1;
        }
        return 0;
    }
}

int apar(trie *rad, char *s)
{
    if (*s == 0)
    {
        return rad->nr1;
    }
   if (rad->nod[*s - 'a'] != NULL ) return apar(rad->nod[*s-'a'],s+1);
    else return 0;
}

int aparpref(trie *rad, char *s)
{
    if (*s == 0)
    {
        return 0;
    }
    if (rad->nod[*s - 'a'] != NULL) return 1 + aparpref(rad->nod[*s - 'a'],s+1);
}

int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");
    root = new trie;
    while(f>>t)
    {
        f.get();
        f.getline(s,NMAX);
        if (t == 0)
        {
            add(root,s);
        }
        else if (t == 1)
        {
            sterge(root,s);
        }
        else if (t == 2)
        {
            g<<apar(root,s)<<"\n";
        }
        else
        {
            g<<aparpref(root,s)<<"\n";
        }
    }
}