Cod sursa(job #1351499)

Utilizator vlady1997Vlad Bucur vlady1997 Data 21 februarie 2015 11:06:14
Problema Trie Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 2.8 kb
            #include <cstdio>
            #include <cstring>
            using namespace std;
            char s[100001];
            struct Trie
            {
                Trie *fii[26];
                int nrap;
                int nrfii;
                Trie ()
                {
                    nrfii=0; nrap=0;
                    for (int i=0; i<26; i++) fii[i]=NULL;
                }
            };
            void insert (Trie *t, char *s)
            {
                if (*s==NULL)
                {
                    t->nrap++;
                    return;
                }
                if (t->fii[s[0]-'a']==NULL)
                {
                    t->fii[s[0]-'a']=new Trie;
                    t->nrfii++;
                }
                insert (t->fii[s[0]-'a'],s+1);
            }
            void remove (Trie *t, char *s)
            {
                if (*s==NULL)
                {
                    t->nrap--;
                    return;
                }
                remove (t->fii[s[0]-'a'],s+1);
                if (t->fii[s[0]-'a']->nrap==0 && t->fii[s[0]-'a']->nrfii==0)
                {
                    t->nrfii--;
                    t->fii[s[0]-'a']=NULL;
                }
            }
            int NrAparitii (Trie *t, char *s)
            {
                if (t==NULL) return 0;
                if (*s==NULL)
                {
                    return t->nrap;
                }
                NrAparitii(t->fii[s[0]-'a'],s+1);
            }
            int prefix (Trie *t, char *s, int k)
            {
                if (t->fii[s[0]-'a']==NULL || *s==NULL)
                {
                    return k;
                }
                else
                {
                    return prefix(t->fii[s[0]-'a'],s+1,k+1);
                }
            }
            int main()
            {
                Trie *t=new Trie;; int p; char z;
                freopen("trie.in","r",stdin);
                freopen("trie.out","w",stdout);
                while (!feof(stdin))
                {
                    memset(s,'\0',sizeof(s));
                    scanf("%d%c",&p,&z);
                    gets(s);
                    if (*s==NULL) continue;
                    if (p==0)
                    {
                        insert(t,s);
                    }
                    else if (p==1)
                    {
                        remove(t,s);
                    }
                    else if (p==2)
                    {
                        printf("%d\n",NrAparitii(t,s));
                    }
                    else if (p==3)
                    {
                        printf("%d\n",prefix(t,s,0));
                    }
                }
                return 0;
            }