Cod sursa(job #2758880)

Utilizator RobertAcAcatrinei Robert-Marian RobertAc Data 13 iunie 2021 21:23:51
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct nod{
    int apar;
    int subtree;
    nod * urm[26];
    nod(){
        apar=0;
        subtree=0;
        for(int i=0;i<26;i++){
            urm[i]=NULL;
        }
    }
};

nod * root=new nod();
void add(nod * n,string s,int poz){
    n->subtree++;
    if(poz==s.size()){
        n->apar++;
        return;
    }
    if(n->urm[s[poz]-'a']==NULL)n->urm[s[poz]-'a']=new nod();
    add(n->urm[s[poz]-'a'],s,poz+1);
}
void rem(nod * n,string s,int poz){
    n->subtree--;
    if(poz==s.size()){
        n->apar--;
        return;
    }
    rem(n->urm[s[poz]-'a'],s,poz+1);
    if(n->urm[s[poz]-'a']->subtree==0){
        delete n->urm[s[poz]-'a'];
        n->urm[s[poz]-'a']=NULL;
    }
}
int query(nod * n,string s,int poz){
    if(poz==s.size())return n->apar;
    if(n->urm[s[poz]-'a']==NULL)return 0;
    if(poz!=s.size())return query(n->urm[s[poz]-'a'],s,poz+1);
}

int query_pref(nod *n,string s,int poz){
    if(poz==s.size())return poz;
    if(n->urm[s[poz]-'a']==NULL)return poz;
    if(poz!=s.size())return query_pref(n->urm[s[poz]-'a'],s,poz+1);
}
int main(){
    int c;
    string s;
    while(in>>c>>s){
        if(c==0)add(root,s,0);
        else if(c==1)rem(root,s,0);
        else if(c==2)out<<query(root,s,0)<<'\n';
        else out<<query_pref(root,s,0)<<'\n';
    }
}