Cod sursa(job #1146162)

Utilizator supermitelArdelean Razvan Mitel supermitel Data 18 martie 2014 19:25:12
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

struct trie
{
    int nf, nc;
    trie *f[30];

    trie()
    {
        nf = nc = 0;
        for(int i = 0; i < 30; i++)
            f[i] = NULL;
    }

    void ins(char *cuv)
    {
        if(cuv[0] == NULL)
        {
            nc++;
            return;
        }
        if(!f[cuv[0]-'a'])
        {
            f[cuv[0]-'a'] = new trie;
            nf++;
        }
        (*f[cuv[0]-'a']).ins(cuv+1);
    }
    void del(char *cuv)
    {
        if(cuv[0] == NULL)
        {
            nc--;
            return;
        }
        (*f[cuv[0]-'a']).del(cuv+1);
        if(f[cuv[0]-'a'] -> nc == 0 && f[cuv[0]-'a'] -> nf == 0)
        {
            nf--;
            delete f[cuv[0]-'a'];
            f[cuv[0]-'a'] = NULL;
        }
    }
    int nrapar(char *cuv)
    {
        if(cuv[0] == NULL)
            return nc;
        return (*f[cuv[0]-'a']).nrapar(cuv+1);
    }
    int lung(char *cuv)
    {
        if(cuv[0] == NULL)
            return 0;
        if(!f[cuv[0]-'a'])
            return 0;
        return 1+f[cuv[0]-'a']->lung(cuv+1);
    }
}t;

int proced;
char s[25];

void solve()
{
    switch(proced)
    {
    case 0:
        t.ins(s);
        break;
    case 1:
        t.del(s);
        break;
    case 2:
        printf("%d\n", t.nrapar(s));
        break;
    case 3:
        printf("%d\n", t.lung(s));
        break;
    }
}

int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    while(!feof(stdin))
    {
        scanf("%d %s\n", &proced, s);
        solve();
    }
    return 0;
}