Cod sursa(job #1964879)

Utilizator ionanghelinaIonut Anghelina ionanghelina Data 13 aprilie 2017 19:24:00
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include<bits/stdc++.h>
#define f(i) (i-'a'+1)
#define maxN 25
using namespace std;
const int sigma=26;
ifstream fin("trie.in");
ofstream fout("trie.out");
char s[maxN];
int op,sol;
struct trie
{
    int cnt,sol;
    trie *sons[sigma+5];
    trie()
    {
        cnt=0;
        sol=0;
        for(int i=1;i<=26;i++)
            sons[i]=NULL;
    }
}*root=new trie();
void Insert(trie *nod,char *s)
{
    nod->cnt++;
    if(*s==NULL)
    {
        nod->sol++;
        return;
    }
    if(!nod->sons[f(s[0])]) nod->sons[f(s[0])]=new trie();
    Insert(nod->sons[f(s[0])],s+1);
}
void Delete(trie *nod,char *s)
{
    nod->cnt--;
    if(*s==NULL)
    {
        nod->sol--;
        return;
    }
    Delete(nod->sons[f(s[0])],s+1);
}
void Query(trie *nod,char *s)
{
    if(*s==NULL)
    {
        fout<<nod->sol<<'\n';
        return;
    }
        else
    {
        if(!nod->sons[f(s[0])])
        {
            fout<<"0\n";
            return;
        }
        Query(nod->sons[f(s[0])],s+1);
    }
}
void PrefixQuery(trie *nod,char *s)
{
    if(*s==NULL)
    {
        fout<<sol<<'\n';
        return;
    }
        else
    {
        if(!nod->sons[f(s[0])] || !nod->sons[f(s[0])]->cnt)
        {
            fout<<sol<<'\n';
            return ;
        }
        sol++;
        PrefixQuery(nod->sons[f(s[0])],s+1);
    }
}
int main()
{
    while(fin>>op)
    {
        fin>>s;
        sol=0;
        if(op==0)
            Insert(root,s);
            else
        if(op==1)
            Delete(root,s);
            else
        if(op==2)
            Query(root,s);
            else
            PrefixQuery(root,s);
    }
    return 0;
}