Cod sursa(job #2664618)

Utilizator gavra_bogdanBogdan Gavra gavra_bogdan Data 28 octombrie 2020 23:36:01
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <cstring>

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

struct Trie {
    int cnt, nr;
    Trie* fiu[26];
    Trie() {
        for (int i = 0; i < 26; i++) fiu[i] = 0;
        cnt = nr = 0;
    }
};

Trie* T = new Trie;
char s[30];
int op;

void insertTrie(Trie* nod, char* s) {
    if (!(*s)) {
        nod->cnt++;
        return;
    }
    int ch = *s - 'a';
    if (!nod->fiu[ch]) nod->nr++, nod->fiu[ch] = new Trie;
    insertTrie(nod->fiu[ch], s + 1);
}

bool deleteTrie(Trie* nod, char* s) {
    int ch = *s - 'a';
    if (!(*s)) nod->cnt--;
    else if (deleteTrie(nod->fiu[ch], s + 1)) nod->fiu[ch] = 0, nod->nr--;
    if (!nod->cnt and !nod->nr and nod != T) {
        delete nod;
        return 1;
    }
    return 0;
}

int lcp(Trie* nod, char* s, int l) {
    int ch = *s - 'a';
    if (!(*s) or !nod->fiu[ch]) return l;
    return lcp(nod->fiu[ch], s + 1, l + 1);
}

int countapp(Trie* nod, char* s) {
    int ch = *s - 'a';
    if (!(*s)) return nod->cnt;
    if (nod->fiu[ch]) return countapp(nod->fiu[ch], s + 1);
    return 0;
}

void solve() {
    if (op == 0) insertTrie(T, s);
    if (op == 1) deleteTrie(T, s);
    if (op == 2) fout << countapp(T, s) << "\n";
    if (op == 3) fout << lcp(T, s, 0) << "\n";
}

int main() {
    while (fin >> op >> s) solve();
}