Cod sursa(job #3220908)

Utilizator Alex_DumitrascuAlex Dumitrascu Alex_Dumitrascu Data 5 aprilie 2024 10:47:03
Problema Trie Scor 45
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 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 let=0;
};

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

void remove_from_trie(string word, int index, trie *tri)
{
    if (index==word.size()-1) return;
    char c=word[index];
    int alp=c-'a';
    if (tri->let==1) {
        delete tri->alfa[alp];
        tri->let--;
        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) {
        //cout<<c;
        index++;
        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) {
            //cout<<word<<endl;
            if (mp[word]==1) remove_from_trie(word, 0, root);
            mp[word]--;
        }
        if (n==2) {
            fout<<mp[word]<<'\n';
        }
        if (n==3) {
            int maxi_siz=0;
            longest_prefix(word, maxi_siz, root);
            //cout<<endl;
            fout<<maxi_siz<<'\n';
        }
    }
    return 0;
}