Cod sursa(job #2091986)

Utilizator smashsmash everything smash Data 20 decembrie 2017 19:04:14
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include<cstring>
using namespace std;
ifstream cin ("trie.in");
ofstream cout ("trie.out");
int poz;
char s[20];
struct trie
{
    int nr,sol;
    trie *fiu[26];
    trie()
    {
        nr=0; sol=0;
        for(int i=0;i<=25;i++) fiu[i]=0;
    }
} *root=new trie();
void add (trie *&that)
{   poz++;
    if(poz==strlen(s)) {that->sol++; return;}
    if(that->fiu[s[poz]-'a']==0) that->fiu[s[poz]-'a']=new trie(),that->nr++;
    add(that->fiu[s[poz]-'a']);
}
void sterge (trie *&that)
{    poz++;
    if(poz==strlen(s)) {that->sol--;
    if(that->sol==0 && that->nr==0 && that!=root)
        delete that;
        that=NULL;
    return;}
    sterge(that->fiu[s[poz]-'a']); poz--;
    if(that->fiu[s[poz]-'a']==0) that->nr--;
    if(that->nr==0 && that!=root)
        delete that,that=NULL;
}
void tipar (trie *&that)
{   poz++;
    if(poz==strlen(s)) {cout<<that->sol<<"\n"; return;}
    if(that->fiu[s[poz]-'a']==0) {cout<<0<<"\n"; return;}
    else tipar(that->fiu[s[poz]-'a']);
}
void last (trie *&that)
{
    poz++;
    if(that->fiu[s[poz]-'a']==0) cout<<poz<<"\n";
    else last(that->fiu[s[poz]-'a']);
}
void  read ()
{ int x;
    while(cin>>x)
    {
        cin>>s; poz=-1;
        if(x==0) add(root);
        else if(x==1) sterge(root);
        else if(x==2) tipar(root);
        else if(x==3) last(root);
    }
}
int main()
{
    read();
    cin.close();
    cout.close();
    return 0;
}