Cod sursa(job #3238303)

Utilizator Cyb3rBoltSbora Ioan-David Cyb3rBolt Data 23 iulie 2024 21:52:31
Problema Trie Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int tip;
string sir;

struct TrieNode {
    TrieNode* copil[26];
    bool finalCuvant;
    int nrCuvinte;
    TrieNode() {
        finalCuvant = false, nrCuvinte = 0;
        for(int i=0; i<26; i++) copil[i] = NULL;
    }
};

class Trie {
private:
    TrieNode* root;
public:
    Trie() { root = new TrieNode(); }
    void adaugareCuvant(string cuvant) {
        TrieNode* nod = root;
        for(char ch : cuvant) {
            int index = ch - 'a';
            if(!nod->copil[index]) nod->copil[index] = new TrieNode();
            nod = nod->copil[index];
        }
        nod->finalCuvant = true, nod->nrCuvinte++;
    }
    bool eUltimNod(TrieNode* nod) {
        for(int i=0; i<26; i++)
            if(nod->copil[i]) return false;
        return true;
    }
    TrieNode* stergereCuvant(TrieNode* nod, string cuvant, int adancime = 0) {
        if(!nod) return NULL;
        if(adancime == cuvant.size()) {
            if(nod->finalCuvant) nod->finalCuvant = false, nod->nrCuvinte--;
            if(eUltimNod(nod) && nod->nrCuvinte == 0) {
                delete (nod);
                nod = NULL;
            }
            return nod;
        }
        else {
            int index = cuvant[adancime] - 'a';
            nod->copil[index] = stergereCuvant(nod->copil[index], cuvant, adancime + 1);
            if(eUltimNod(nod) && nod->finalCuvant == false && nod->nrCuvinte == 0) {
                delete (nod);
                nod = NULL;
            }
            return nod;
        }
    }
    void stergereCuvant(string cuvant) { stergereCuvant(root, cuvant); }
    int longestPrefix(string cuvant) {
        TrieNode* nod = root;
        int cnt = 0;
        for(char ch : cuvant) {
            int index = ch - 'a';
            if(!nod->copil[index]) return cnt;
            nod = nod->copil[index], cnt++;
        }
        return cnt;
    }
    int gasireCuvinte(string cuvant) {
        TrieNode* nod = root;
        for(char ch : cuvant) {
            int index = ch - 'a';
            if(!nod->copil[index]) return 0;
            nod = nod->copil[index];
        }
        return nod->nrCuvinte;
    }
};

int main()
{
    Trie trie;
    while(fin >> tip >> sir) {
        if(tip == 0) trie.adaugareCuvant(sir);
        else if(tip == 1) trie.stergereCuvant(sir);
        else if(tip == 2) fout << trie.gasireCuvinte(sir) << '\n';
        else fout << trie.longestPrefix(sir) << '\n';
    }

    return 0;
}