Cod sursa(job #1821772)

Utilizator tqmiSzasz Tamas tqmi Data 3 decembrie 2016 16:52:08
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int op;
char cuv[30];
struct Trie
{
    int cont;
    int nrSons;
    Trie *son[26];

    Trie(){
        cont=nrSons=0;
        memset(son,0,sizeof(son));
    }
};
Trie *T = new Trie;
void add(Trie *nod, char *word)
{
    if(*word=='\0')
    {
        nod->cont++;
        return;
    }
    if(nod->son[*word-'a']==0)
    {
        nod->son[*word-'a'] = new Trie;
        nod->nrSons++;
    }
    add(nod->son[*word-'a'],word+1);
}
int del(Trie *nod, char *word)
{
    if(*word=='\0')
    {
        nod->cont--;
    }
    else if(del(nod->son[*word-'a'],word+1))
    {
        nod->son[*word-'a']=0;
        nod->nrSons--;
    }
    if(nod->cont==0 && nod->nrSons==0 && nod!=T)
    {
        delete nod;
        return 1;
    }
    return 0;
}
int getApp(Trie *nod,char *word)
{
    if(*word=='\0')
        return nod->cont;
    if(nod->son[*word-'a'])
        return getApp(nod->son[*word-'a'],word+1);
    return 0;
}
int getPrefix(Trie *nod, char *word,int nr)
{
    if(*word=='\0' || nod->son[*word-'a']==0)
        return nr;
    return getPrefix(nod->son[*word-'a'],word+1,nr+1);
}
void run()
{
    fin>>op;
    fin>>cuv;
    while(!fin.eof())
    {
        switch(op)
        {
        case 0:
            add(T,cuv);
            break;
        case 1:
            del(T,cuv);
            break;
        case 2:
            fout<<getApp(T,cuv)<<"\n";
            break;
        case 3:
            fout<<getPrefix(T,cuv,0)<<"\n";
            break;
        }
        fin>>op;
        fin>>cuv;
    }
}
int main()
{
    run();
    return 0;
}