Cod sursa(job #2026218)

Utilizator Alex18maiAlex Enache Alex18mai Data 23 septembrie 2017 22:41:34
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>

using namespace std;

ifstream cin ("trie.in");
ofstream cout ("trie.out");

const int lit = 26;

struct node{
    node(){
        ap = 0;
        pref = 0;
        for (int i=0; i<lit; i++){
            next[i] = NULL;
        }
    }
    int ap;
    int pref;
    node *next [lit];
};

void add_word (node *prev , string word , int pos){
    if (pos == word.size()){
        return;
    }
    if (prev -> next[word[pos] - 'a'] == NULL){
        prev -> next[word[pos] - 'a'] = new node();
    }
    prev = prev -> next[word[pos] - 'a'];
    prev -> pref ++;
    if (pos == word.size() - 1){
        prev -> ap ++;
    }
    add_word (prev , word , pos + 1);
}

void delete_word (node *prev , string word , int pos){
    if (pos == word.size()){
        return;
    }
    node *old = prev;
    prev = prev -> next[word[pos] - 'a'];
    prev -> pref --;
    if (pos == word.size() - 1){
        prev -> ap --;
        if (prev -> pref == 0 && prev -> ap == 0){
            delete prev;
            old -> next[word[pos] - 'a'] = NULL;
        }
    }
    delete_word (prev , word , pos + 1);
}

int ap_word (node *prev , string word , int pos){
    prev = prev -> next[word[pos] - 'a'];
    if (prev == NULL){
        return 0;
    }
    if (pos == word.size() - 1){
        return (prev -> ap);
    }
    return ap_word (prev , word , pos + 1);
}

int pref_word (node *prev , string word , int pos , int lung){
    prev = prev -> next[word[pos] - 'a'];
    if (prev == NULL || prev -> pref == 0){
        return lung;
    }
    lung ++;
    if (pos == word.size() - 1){
        return lung;
    }
    return pref_word (prev , word , pos + 1, lung);
}


int main() {

    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int test;
    string word;
    node *root = new node();

    while(cin>>test){
        cin>>word;
        if (test == 0){
            add_word(root , word , 0);
        }
        if (test == 1){
            delete_word(root , word , 0);
        }
        if (test == 2){
            int ans = ap_word(root , word , 0);
            cout<<ans<<'\n';
        }
        if (test == 3){
            int ans = pref_word(root , word , 0 , 0);
            cout<<ans<<'\n';
        }
    }
    return 0;
}