Cod sursa(job #1875386)

Utilizator Emil64Emil Centiu Emil64 Data 11 februarie 2017 00:51:41
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>

using namespace std;

class Trie{

    Trie* fii[28];
    int nf, a;
    public:
        Trie(){
            this->nf = 0;
            this->a = 0;
            for(int i=0; i<28; i++, this->fii[i] = __null);
        }
        void update(char* c, int op){

            if(!strlen(c)){
                this->a+=op;
                return;
            }
            if(!this->fii[c[0]-'a']){
                nf++;
                this->fii[c[0]-'a'] = new Trie();
            }

            this->fii[c[0]-'a']->update(c+1, op);

            if(op == -1 && !this->fii[c[0]-'a']->a && !this->fii[c[0]-'a']->nf){
                this->nf--;
                this->fii[c[0]-'a'] = __null;
            }
        }
        int q1(char *c){
            if(!strlen(c))
                return this->a;
            if(!this->fii[c[0]-'a'])
                return 0;
            return this->fii[c[0]-'a']->q1(c+1);
        }
        int q2(char* c, int p){
            if(!strlen(c) || !this->fii[c[0]-'a']) return p;
            return this->fii[c[0]-'a']->q2(c+1, p+1);
        }
};

int main()
{
    ifstream f("trie.in");
    ofstream g("trie.out");
    int cr;
    char s[28]="";
    Trie* t = new Trie();
    f >> cr >> s;
    while(!f.eof()){
        if(cr == 0) t->update(s, 1);
        else if(cr == 1) t->update(s, -1);
        else if(cr == 2) g << t->q1(s) << "\n";
        else g << t->q2(s, 0) << "\n";
        f >> cr >> s;
    }
}