Cod sursa(job #2285092)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 18 noiembrie 2018 09:27:00
Problema Trie Scor 100
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.83 kb
//
//  Trie.cpp
//
//
//  Created by Raoul Bocancea on 14/11/2018.
//

 #include <fstream>

 #define l (*lit - 'a')
 
 const std :: string programName = "trie";
 std :: ifstream f(programName + ".in");
 std :: ofstream g(programName + ".out");

class Trie {
public:
    Trie* sons[26];
    int no_sons, no_words;
    Trie() {
        no_sons = no_words = NULL;
        for (size_t i = 0; i <= 25; ++i)
            sons[i] = NULL;
    }
    
    void ins(char* lit) {
        if (*lit) {
            if (sons[l] == NULL) {
                no_sons++;
                sons[l] = new Trie;
            }
            sons[l]->ins(lit + 1);
        } else
            no_words++;
    }
    
    bool del(char* lit) {
        if (*lit == NULL)
            --no_words;
        else if (sons[l]->del(lit + 1)) {
            delete sons[l];
            sons[l] = 0;
            no_sons--;
        }
        if (no_words or no_sons)
            return false;
        return true;
    }
    
    int nr_app(char* lit) {
        if (*lit) {
            if (sons[l])
                return sons[l]->nr_app(lit + 1);
            return 0;
        }
        return no_words;
    }
    
    int pref(char* lit, int size) {
        if (*lit == NULL)
            return size;
        if (sons[l])
            return sons[l]->pref(lit + 1, size + 1);
        return size;
    }
    
};

int main(void) {
    Trie trie = Trie();
    char s[21];
    int quest;
    while (f >> quest >> s)
        switch (quest) {
            case 0:
                trie.ins(s);
                break;
            case 1:
                trie.del(s);
                break;
            case 2:
                g << trie.nr_app(s) << '\n';
                break;
            case 3:
                g << trie.pref(s, 0) << '\n';
                break;
        }
    return 0x0;
}