Cod sursa(job #1720446)

Utilizator mariusadamMarius Adam mariusadam Data 22 iunie 2016 15:58:54
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#include <fstream>
#include <cstring>
#include <stdio.h>
#include <string.h>

using namespace std;

class Trie {
private:
    int nrFii;
    int nrCuv;
    Trie* fii[26];

    void addRec(Trie *nod, char *s) {
        if(*s == 0) {
            nod->nrCuv++;
            return;
        }
        if(nod->fii[*s - 'a'] == NULL) {
            nod->fii[*s - 'a'] = new Trie();
            nod->nrFii++;
        }
        addRec(nod->fii[*s - 'a'], s + 1);
    }

    bool delRec(Trie *nod, char *s) {
        if(*s == 0) {
            nod->nrCuv--;
        } else {
            if(delRec(nod->fii[*s - 'a'], s + 1)) {
                nod->fii[*s - 'a'] = 0;
                nod->nrFii--;
            }
        }
        if(nod->nrFii == 0 && nod->nrCuv == 0 && nod != this) {
            delete nod;
            return true;
        }
        return false;
    }

    int freqRec(Trie *nod, char *s) {
        if(*s == 0) {
            return nod->nrCuv;
        }
        if(nod->fii[*s - 'a'] != 0) {
            return freqRec(nod->fii[*s - 'a'], s + 1);
        }
        return 0;
    }

    int lgPrefixRec(Trie *nod, char *s) {
        if(*s == 0 || nod->fii[*s - 'a'] == 0) {
            return 0;
        }
        return lgPrefixRec(nod->fii[*s - 'a'], s + 1) + 1;
    }
public:
    Trie() {
        nrFii = 0;
        nrCuv = 0;
        memset(fii, 0, sizeof(fii));
    }
    ~Trie() {
        for(int i = 0; i < 26; i++) {
            if(this->fii[i] != NULL) {
                delete this->fii[i];
            }
        }
    }
    void add(char *s) {
        this->addRec(this, s);
    }
    void del(char *s) {
        this->delRec(this, s);
    }
    int freq(char *s) {
        return this->freqRec(this, s);
    }
    int lgPrefix(char *s) {
        return lgPrefixRec(this, s);
    }
};

int main() {
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    Trie t;
    char line[30];
    while(fin.getline(line, 30)) {
        switch(line[0]) {
        case '0' : t.add(line + 2); break;
        case '1' : t.del(line + 2); break;
        case '2' : fout << t.freq(line + 2) << "\n"; break;
        case '3' : fout << t.lgPrefix(line + 2) <<"\n"; break;
        default : break;
        }
    }
    fin.close();
    fout.close();
    return 0;
}