Cod sursa(job #2472848)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 13 octombrie 2019 00:10:42
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

struct Trie{
    int nrw, nrs;
    Trie *son[26];
    Trie(){
        nrw = nrs = 0;
        for (int i = 0; i < 26; i++)
            son[i] = 0;
    }
};
Trie *trie = new Trie;
char c[25];

void Insert(char word[], Trie *p){
    if (!word[0]){
        p->nrw++;
        return;
    }
    int ind = word[0] - 'a';
    if (!p->son[ind]){
        p->son[ind] = new Trie;
        p->nrs++;
    }
    Insert(word + 1, p->son[ind]);

}

int Delete(char word[], Trie *p){
    if (!word[0])
        p->nrw--;
    else{
        int ind = word[0] - 'a';
        if (Delete(word + 1, p->son[ind])){
            p->nrs--;
            p->son[ind] = 0;
        }
    }
    if (!p->nrs && !p->nrw && p != trie){
        delete p;
        return 1;
    }
    return 0;
}

int Print(char word[], Trie *p){
    if (!word[0])
        return p->nrw;
    int ind = word[0] - 'a';
    if (!p->son[ind])
        return 0;
    return Print(word + 1, p->son[ind]);
}

int Prefix(char word[], Trie *p, int nr){
    if (!word[0])
        return nr;
    int ind = word[0] - 'a';
    if (!p->son[ind])
        return nr;
    return Prefix(word + 1, p->son[ind], nr + 1);
}

int main(){
    while (fin.getline(c, 25)){
        if (c[0] == '0')
            Insert(c + 2, trie);
        if (c[0] == '1')
            Delete(c + 2, trie);
        if (c[0] == '2')
            fout << Print(c + 2, trie) << '\n';
        if (c[0] == '3')
            fout << Prefix(c + 2, trie, 0) << '\n';
    }
    return 0;
}