Cod sursa(job #1065705)

Utilizator danny794Dan Danaila danny794 Data 23 decembrie 2013 16:35:07
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <cstdio>
#include <string>

using namespace std;

#define MAXN 26

typedef struct trie {
    int words, prefix;
    trie *child[MAXN];
} trie;

trie *t = new trie;

void read() {
    freopen( "trie.in", "r", stdin );
    freopen( "trie.out", "w", stdout );
}

void add(char *s, trie *tree) {
    if (s[0] < 'a' || s[0] > 'z') {
        tree -> words++;
    } else {
        int index = s[0] - 'a';

        if(!tree -> child[index])
            tree -> child[index] = new trie;

        tree -> prefix++;
        add(s + 1, tree -> child[index]);
    }
}

trie* remove(char *s, trie *tree) {
    if (s[0] < 'a' || s[0] > 'z') {
        tree -> words--;
    } else {
        int index = s[0] - 'a';
        tree -> prefix--;
        if(tree -> child[index] == 0)
            return tree;
        tree -> child[index] = remove(s + 1, tree -> child[index]);
    }

    if (tree -> words == 0 && tree -> prefix == 0)
        return 0;

    return tree;
}

int search_words(char *s, trie *tree) {
    if (s[0] < 'a' || s[0] > 'z') {
        return tree -> words;
    } else {
        int index = s[0] - 'a';
        if (!tree -> child[index])
            return 0;
        else
            return search_words(s + 1, tree -> child[index]);
    }
}

int search_prefixes(char *s, trie *tree) {
    if (s[0] < 'a' || s[0] > 'z') {
        return 0;
    } else {
        int index = s[0] - 'a';
        if (!tree -> child[index])
            return 0;
        else
            return 1 + search_prefixes(s + 1, tree -> child[index]);
    }
}

void solve() {
    char s[26];
    int k;
    while(scanf("%d %s", &k, s) == 2) {
        switch(k){
            case 0: add(s, t); break;
            case 1: remove(s, t); break;
            case 2: printf("%d\n", search_words(s, t)); break;
            case 3: printf("%d\n", search_prefixes(s, t)); break;
        }
    }
}

int main() {
    read();
    solve();
    return 0;
}