Cod sursa(job #2089313)

Utilizator sergiudnyTritean Sergiu sergiudny Data 16 decembrie 2017 12:39:04
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");

struct Trie{
    int cnt,nrs;
    Trie *fiu[26];
    Trie(){
        cnt=nrs=0;
        memset(fiu,0,sizeof(fiu));
    }
};

char cuv[35];
Trie *root = new Trie();
int V;

void add(char *p, Trie *nod){
    if(*p == NULL){
        nod->cnt++;
        return;
    }
    int delta = *p - 'a';
    if(nod->fiu[delta] == NULL){
        nod->fiu[delta] = new Trie();
        nod->nrs++;
    }
    add(p+1, nod->fiu[delta]);
}

int freq(char *p, Trie *nod){
    if(*p == NULL)
        return nod->cnt;
    int delta = *p - 'a';
    if(nod->fiu[delta] == NULL)
        return 0;
    freq(p+1, nod->fiu[delta]);
}

int pref(char *p, Trie *nod){
    if(*p == NULL)
        return 0;
    int delta = *p-'a';
    if(nod->fiu[delta] == NULL)
        return 0;
    return pref(p+1,nod->fiu[delta])+1;
}

bool _erase(char *p, Trie *nod){
    if(*p == NULL){
        nod->cnt--;
        if(nod->cnt == 0 && nod->nrs == 0 && nod!=root){
            delete nod;
            return 1;
        }
        return 0;
    }
    int delta = *p-'a';
    if(_erase(p+1, nod->fiu[delta])){
        nod->nrs--;
        nod->fiu[delta]=0;
        if(nod->cnt == 0 && nod->nrs == 0 && nod!=root){
            delete nod;
            return 1;
        }
    }
    return 0;
}

int main()
{
    while(fin>>V>>cuv){
        if(!V) add(cuv, root);
        if(V==1) _erase(cuv, root);
        if(V==2) fout<<freq(cuv, root)<<'\n';
        if(V==3) fout<<pref(cuv, root)<<'\n';
    }
    return 0;
}