Cod sursa(job #2720824)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 11 martie 2021 12:18:02
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

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

const int LMax = 20;

struct Trie{
    int nrwords, nrsons;
    Trie *son[26];
    Trie(){
        nrwords = nrsons = 0;
        for (int i = 0; i < 26; i++)
            son[i] = 0;
    }
};
Trie *trie = new Trie;
char word[LMax + 5];

void Insert(char word[], Trie *t){
    if (!word[0]){
        t->nrwords++;
        return;
    }
    int letter = word[0] - 'a';
    if (!t->son[letter]){
        t->son[letter] = new Trie;
        t->nrsons++;
    }
    Insert(word + 1, t->son[letter]);
}

int Delete(char word[], Trie *t){
    if (!word[0])
        t->nrwords--;
    else{
        int letter = word[0] - 'a';
        if (Delete(word + 1, t->son[letter])){
            t->nrsons--;
            t->son[letter] = 0;
        }
    }
    if (!t->nrwords && !t->nrsons && t != trie){
        delete t;
        return 1;
    }
    return 0;
}

void Print(char word[], Trie *t){
    if (!word[0]){
        fout << t->nrwords << '\n';
        return;
    }
    int letter = word[0] - 'a';
    if (!t->son[letter]){
        fout << 0 << '\n';
        return;
    }
    Print(word + 1, t->son[letter]);
}

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

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