Cod sursa(job #3190636)

Utilizator stefanvilcescuStefan Vilcescu stefanvilcescu Data 7 ianuarie 2024 19:38:17
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>

using namespace std;
const int MAXN=2e5;
const int MAXM=2e5;

class Trie{
    private:
        int cntcuv=0, cntsuf=0;
        Trie *copii[26]={};
    public:
        void insert(string s, int poz){
            cntsuf++;
            if(poz==(int)s.size())
                cntcuv++;
            else{
                if(copii[s[poz]-'a']==0)
                    copii[s[poz]-'a']=new Trie;
                copii[s[poz]-'a']->insert(s, poz+1);
            }
        }
        void erase(string s, int poz){
            cntsuf--;
            if(poz==(int)s.size())
                cntcuv--;
            else{
                copii[s[poz]-'a']->erase(s, poz+1);
                if(copii[s[poz]-'a']->cntsuf==0){
                    delete copii[s[poz]-'a'];
                    copii[s[poz]-'a']=NULL;
                }
            }
        }
        int count(string s, int poz){
            if(poz==(int)s.size())
                return cntcuv;
            if(copii[s[poz]-'a']==0)
                return 0;
            return copii[s[poz]-'a']->count(s, poz+1);
        }
        int countPrefComun(string s, int poz){
            if(poz==(int)s.size())
                return poz;
            if(copii[s[poz]-'a']==0)
                return poz;
            return copii[s[poz]-'a']->countPrefComun(s, poz+1);
        }
};

Trie trie;

signed main(){
	ifstream cin("trie.in");
    ofstream cout("trie.out");
	int tip;
	string s;
	while(cin>>tip>>s){
        if(tip==0)
            trie.insert(s, 0);
        else if(tip==1)
            trie.erase(s, 0);
        else if(tip==2)
            cout<<trie.count(s, 0)<<"\n";
        else
            cout<<trie.countPrefComun(s, 0)<<"\n";
	}
	return 0;
}