Cod sursa(job #2250847)

Utilizator pinteastefanPintea Teodor Stefan pinteastefan Data 30 septembrie 2018 19:16:20
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>

using namespace std;

struct trie{
    int cuvant;
    int prefix;
    trie *nxt[26];
    trie(){
        cuvant = 0 ;
        prefix = 0;
        memset(nxt, 0, sizeof(nxt));
    }
};
trie *Root = new trie();
void insert (string &word, int position, trie *& nod)
{
    nod -> prefix += 1;
    if (position == word.size())
    {
        nod -> cuvant += 1;
        return;
    }
    int where = word [position] - 'a';
    if (nod -> nxt[where] == nullptr)
        nod -> nxt[where] = new trie();
    insert(word, position + 1, nod -> nxt[where]);
}
void stergere (string &word, int position, trie *& nod)
{
    nod -> prefix -= 1;
    if (position == word.size()){
        nod ->cuvant -= 1;
        if (nod -> prefix == 0) {
            delete nod;
            nod = nullptr;
        }
        return;
    }
    int where = word[position] - 'a';
    stergere(word, position + 1, nod -> nxt[where]);
    if (nod!= Root and nod -> prefix == 0){
        delete nod;
        nod = nullptr;
    }
}
int count (string &word, int position, trie *& nod)
{
    if(position == word.size()){
        return nod -> cuvant;
    }
    int where = word[position] - 'a';
    if (nod->nxt[where] == nullptr) return 0;
    return count(word, position + 1, nod -> nxt[where]);
}
int longest (string &word, int position, trie *& nod)
{
    if (position == word.size()) return 0;
    int where = word [position] - 'a';
    if (nod -> nxt[where] == nullptr or nod->nxt[where]->prefix == 0){
        return 0;
    }
    return 1 + longest(word, position + 1, nod -> nxt[where]);
}
int main() {
    ifstream f ("trie.in");
    ofstream g("trie.out");
    int op, pos = 0;
    string s;
    while (f >> op >> s){
        if (op == 0){
            insert(s, 0, Root);
        }
        if (op == 1){
            stergere(s, 0, Root);
        }
        if (op == 2){
            g << count(s, 0, Root) << "\n";
        }
        if (op == 3){
            g << longest(s, 0, Root) << "\n";
        }
    }
    return 0;
}