Cod sursa(job #767367)

Utilizator test_666013Testez test_666013 Data 13 iulie 2012 13:37:13
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>
#include <cctype>


struct trie{
    struct trie * f[26];
    int nr,cuv; }*t;

char s[30];

void add(char *s){
    trie * g = t;
    int urm;
    while( isalpha(*s) )
    {
        urm = *s - 'a';
        if( g->f[urm] == 0 ) g->f[urm] = new trie;
        g = g->f[urm];
        g->nr++;
        s++;
    }
        g->cuv++;
}

void remove(char *s){
    trie * g = t;
    int urm;
    while( isalpha(*s) )
    {
        urm = *s - 'a';
        g = g->f[urm];
        g->nr--;
        s++;
    }
        g->cuv--;
}

int aparitii(char *s){
    trie *g = t;
    int urm;
    while( isalpha(*s) )
    {
        urm = *s - 'a';
        if(g->f[urm] == 0) return 0;
        g = g->f[urm];
        s++;
    }
        return g->cuv;
}

int prefix(char *s){
    trie *g = t;
    int urm, l = 0;
    while( isalpha(*s) )
    {
        urm = *s - 'a';
        if(g->f[urm] == 0)return l;
        g = g->f[urm];
        if(g->nr == 0)return l;
        l++;
        s++;
    }
        return l;
    }

int main(){
    int c;
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    t = new trie;
        while( scanf("%d %s ",&c,s) != -1 )
        {
            switch(c)
            {
                case 0 : add(s); break;
                case 1 : remove(s); break;
                case 2 : printf("%d\n",aparitii(s)); break;
                case 3 : printf("%d\n",prefix(s)); break;
            }
        }
    return 0;
}