Cod sursa(job #2282993)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 14 noiembrie 2018 20:14:43
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 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:
    int no_words, no_sons;
    Trie* sons[26];
    
    Trie() {
        no_words = no_sons = 0;
        for (int i = 0; i < 26; ++i)
            sons[i] = 0;
    }
    
    void ins(char *lit) {
        if (*lit) {
            if (!sons[l]) {
                ++no_sons;
                sons[l] = new Trie;
            }
            sons[l]->ins(lit + 1);
        }
        else
            ++no_words;
    }
    
    bool del(char *lit) {
        if (!*lit)
            --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 nap(char *lit) {
        if (*lit) {
            if (sons[l])
                return sons[l]->nap(lit + 1);
            return 0;
        }
        return no_words;
    }
    
    int pref(char *lit, int size) {
        if (!*lit)
            return size;
        if (sons[l])
            return sons[l]->pref(lit + 1, size + 1);
        return size;
    }
};

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