Cod sursa(job #2825491)

Utilizator Ioana_GaborGabor Ioana Ioana_Gabor Data 4 ianuarie 2022 19:40:24
Problema Trie Scor 5
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb

#include <bits/stdc++.h>
#define LMAX 20
#define ALPHA 26

using namespace std;

ifstream fi("trie.in");
ofstream fo("trie.out");

struct trie{
    int cnt,ap;
    trie *sons[ALPHA];
    trie(){
        cnt=ap=0;
        for(int i=0;i<ALPHA;i++){
            sons[i]=NULL;
        }
    }
} *root, *where;

int t,l;
char sir[LMAX+5];

void add_word(){
    where=root;
    for(int i=0;i<l;i++){
        if(where->sons[sir[i]-'a']==NULL){
            where->sons[sir[i]-'a']=new trie;
        }
        where=where->sons[sir[i]-'a'];
        where->cnt++;
    }
    where->ap++;
}

bool delete_word(int ind,trie *it){
    if(ind==l-1){
        it->ap--;
        it->cnt--;
        if(it->cnt==0){
            delete it;
            return true;
        }
        return false;
    }
    if(delete_word(ind+1,it->sons[sir[ind+1]-'a'])){
        it->sons[sir[ind+1]-'a']=NULL;
    }
    it->cnt--;
    if(it->cnt==0){
        delete it;
        return true;
    }
    return false;
}

int ap_word(){
    where=root;
    for(int i=0;i<l;i++){
        if(where->sons[sir[i]-'a']==NULL){
            return false;
        }
        where=where->sons[sir[i]-'a'];
    }
    return where->ap;
}

int prefix_length(){
    where=root;
    for(int i=0;i<l;i++){
        if(where->sons[sir[i]-'a']==NULL){
            return i;
        }
        where=where->sons[sir[i]-'a'];
    }
    return 0;
}

void solve(){
    root = new trie;
    while(fi>>t>>sir){
        l=strlen(sir);
        if(t==0){
            add_word();
        }else if(t==1){
            if(delete_word(0,root->sons[sir[0]-'a'])){
                root->sons[sir[0]-'a']=NULL;
            }            
        }else if(t==2){
            fo<<ap_word()<<'\n';
        }else if(t==3){
            fo<<prefix_length()<<'\n';
        }
    }
}

int main(){
    solve();
    fi.close();
    fo.close();
}