Cod sursa(job #996181)

Utilizator FlameingoAiordachioaei Marius Flameingo Data 11 septembrie 2013 11:48:38
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <cstdio>
#include <iostream>
using namespace std;

const int ALPH = 26;

struct trie_node {

    int key, son_nr;
    trie_node *son[ALPH];
    trie_node () {

        key = son_nr = 0;
        for (int i = 0; i < ALPH; ++i)
            son[i] = 0;

    }

};

trie_node *root = new trie_node;
int r;

void TRIE_push (char *s) {

    trie_node *current = root;
    for (; *s; ++s) {
        if (!current->son[*s - 'a'])
            current->son[*s - 'a'] = new trie_node,
            current->son_nr++;
        current = current->son[*s - 'a'];
    }
    current->key++;

}

void TRIE_pop (char *s, trie_node *current) {

    if (!*s) {
        current->key--;
        return;
    }
    TRIE_pop (s + 1, current->son[*s - 'a']);
    if (!current->son[*s - 'a']->key && !current->son[*s - 'a']->son_nr)
        delete current->son[*s - 'a'],
        current->son[*s - 'a'] = 0,
        current->son_nr--;

}

int TRIE_query (char *s) {

    trie_node *current = root;
    for (; *s && current; ++s)
        current = current->son[*s - 'a'];
    if (!current)
        return 0;
    return current->key;

}

void TRIE_prefix (char *s) {

    trie_node *current = root;
    for (; *s && current; ++s, ++r)
        current = current->son[*s - 'a'];

}

int main () {

    freopen ("trie.in", "r", stdin);
    freopen ("trie.out", "w", stdout);
    int t;
    char S[21];
    while (cin >> t >> S)
        switch (t) {
        case 0:
            TRIE_push (S); break;
        case 1:
            TRIE_pop (S, root); break;
        case 2:
            cout << TRIE_query (S) << '\n'; break;
        default:
            r = 0;
            TRIE_prefix (S);
            cout << r - 1 << '\n';
        }

}