Cod sursa(job #2681781)

Utilizator Katherine456719Swan Katherine Katherine456719 Data 6 decembrie 2020 17:56:51
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
using namespace std;

struct Nod{
    Nod* fii[26];
    int contor;
    Nod(){
        contor = 0;
        for(int i = 0;i < 26; ++i)
            fii[i] = nullptr;
    }
};

void insertn(Nod * node, string s){
    node->contor += 1;
    for( auto x : s){
        int poz = x - 'a';
        if(node -> fii[poz] == nullptr)
            node->fii[poz] = new Nod();
        node = node->fii[poz];
        node->contor += 1;
    }
}

void erasen(Nod * node, string s)
{
    node->contor -= 1;
    for( auto x : s){
        int poz =x - 'a';
        node = node->fii[poz];
        node->contor -= 1;
    }
}

int countn(Nod *nod,string s)
{
    for(auto x : s) {
        int poz = x - 'a';
        if (nod->fii[poz] == nullptr) return 0;
        nod = nod->fii[poz];
    }
    int ans = nod -> contor;
    for(int i = 0; i < 26; ++i)
        if(nod -> fii[i] != nullptr)
            ans -= nod->fii[i]->contor;
    return ans;
}

int prefix(Nod *nod,string s){
    int lungime = 0;
    for(auto x : s){
        int poz = x - 'a';
        if(nod->fii[poz] == nullptr or nod->fii[poz]->contor == 0)
            return lungime;
        nod = nod->fii[poz];
        lungime ++;
    }
    return lungime;
}

int main() {
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    Nod *root = new Nod();
    int type;
    string s;
    while(fin >> type >> s){
        if(type == 0)
            insertn(root,s);
        else if(type == 1)
            erasen(root,s);
        else if(type == 2)
            fout << countn(root,s) << "\n";
        else
            fout << prefix(root,s) << "\n";
    }
    return 0;
}