Cod sursa(job #1404738)

Utilizator 4ONI2015oni2015 4ONI2015 Data 28 martie 2015 15:06:21
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;
char s[25];
int t;
struct nod
{
    int f, viz;
    nod *fiu[30];
    nod()
    {
        f = viz = 0;
        for(int i = 0; i <= 26; i++)
            fiu[i] = 0;
    }
}*root, *trie;
void adauga()
{
    trie = root;
    for(int i = 0; s[i]; i++)
    {
        if(!trie->fiu[s[i] - 'a'])
            trie->fiu[s[i] - 'a'] = new nod;
        trie = trie->fiu[s[i] - 'a'];
        trie->viz++;
    }
    trie->f++;
}
void sterge()
{
    trie = root;
    for(int i = 0; s[i]; i++)
    {
        if(!trie->fiu[s[i] - 'a'])
            return;
        trie = trie->fiu[s[i] - 'a'];
        trie->viz--;
    }
    trie->f--;
}
void nrapar()
{
    trie = root;
    for(int i = 0; s[i]; i++)
    {
        if(!trie->fiu[s[i] - 'a'] || !trie->fiu[s[i] - 'a']->viz)
        {
            printf("0\n");
            return;
        }
        trie = trie->fiu[s[i] - 'a'];
    }
    printf("%d\n", trie->f);
}
void prefix()
{
    int sol = 0;
    trie = root;
    for(int i = 0; s[i]; i++)
    {
        if(!trie->fiu[s[i] - 'a'] || !trie->fiu[s[i] - 'a']->viz)
        {
            printf("%d\n", sol);
            return;
        }
        trie = trie->fiu[s[i] - 'a'];
        sol++;
    }
    printf("%d\n", sol);
}
int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);
    root = new nod;
    while(scanf("%d", &t)==1)
    {
        scanf("%s", &s);
        if(!t)
        {
            adauga();
            continue;
        }
        if(t == 1)
        {
            sterge();
            continue;
        }
        if(t == 2)
        {
            nrapar();
            continue;
        }
        prefix();
    }
    return 0;
}