Cod sursa(job #3220920)

Utilizator Alex_DumitrascuAlex Dumitrascu Alex_Dumitrascu Data 5 aprilie 2024 11:25:16
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;

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

unordered_map <string, int> mp;

struct trie
{
    trie *alfa[26]={};
    int occ[26]={};
};

//int cnt=0, in=0;

void add_to_trie (string word, int index, trie *tri) {
    if (index==word.size()) return;
    char c=word[index];
    int alp=c-'a';
    tri->occ[alp]++;
    if (tri->alfa[alp]==nullptr) {
        trie *ne=new trie;
        tri->alfa[alp]=ne;
    }
    add_to_trie(word, index+1, tri->alfa[alp]);
}

void remove_from_trie(string word, int index, trie *tri)
{
    if (index==word.size()) return;
    char c=word[index];
    int alp=c-'a';
    tri->occ[alp]--;
    if (tri->occ[alp]==0) {
        delete tri->alfa[alp];
        tri->alfa[alp] = nullptr;
        return;
    }
    remove_from_trie(word, index+1, tri->alfa[alp]);
}
void longest_prefix (string word, int &index, trie *tri)
{
    if (index==word.size()) return;
    char c=word[index];
    int alp=c-'a';
    if (tri->alfa[alp]!=nullptr) {
        index++;
        //if (cnt==13786) cout<<c<<' '<<tri->occ[alp]<<endl;
        longest_prefix(word, index, tri->alfa[alp]);
    }
}
int main()
{
    fin.tie(0); fin.sync_with_stdio(false);
    int n; string word;
    trie *root=new trie;
    while (fin>>n>>word) {
        if (n==0) {
            if (mp[word]==0) add_to_trie(word, 0, root);
            mp[word]++;
        }
        if (n==1) {
            if (mp[word]>0) mp[word]--;
            if (mp[word]==0) remove_from_trie(word, 0, root);
        }
        if (n==2) {
            fout<<mp[word]<<'\n';
        }
        if (n==3) {
            int maxi_siz=0;
            longest_prefix(word, maxi_siz, root);
            fout<<maxi_siz<<'\n';
        }
    }
    delete root;
    return 0;
}