Cod sursa(job #3190786)

Utilizator stefanvilcescuStefan Vilcescu stefanvilcescu Data 8 ianuarie 2024 02:14:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <bits/stdc++.h>

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

int val[127];

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[val[(int)s[poz]]]==0)
                    copii[val[(int)s[poz]]]=new Trie;
                copii[val[(int)s[poz]]]->insert(s, poz+1);
            }
        }
        void erase(string s, int poz){
            cntsuf--;
            if(poz==(int)s.size())
                cntcuv--;
            else{
                copii[val[(int)s[poz]]]->erase(s, poz+1);
                if(copii[val[(int)s[poz]]]->cntsuf==0){
                    delete copii[val[(int)s[poz]]];
                    copii[val[(int)s[poz]]]=NULL;
                }
            }
        }
        int count(string s, int poz){
            if(poz==(int)s.size())
                return cntcuv;
            if(copii[val[(int)s[poz]]]==0)
                return 0;
            return copii[val[(int)s[poz]]]->count(s, poz+1);
        }
        int countPrefComun(string s, int poz){
            if(poz==(int)s.size())
                return poz;
            if(copii[val[(int)s[poz]]]==0)
                return poz;
            return copii[val[(int)s[poz]]]->countPrefComun(s, poz+1);
        }
};

Trie trie;

signed main(){
	ifstream cin("trie.in");
    ofstream cout("trie.out");
	int tip, i;
	string s;
	for(i=0; i<26; i++)
        val[i+'a']=i;
	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;
}