Cod sursa(job #2282975)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 14 noiembrie 2018 19:56:44
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 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;
    }
}t;

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