Cod sursa(job #581793)

Utilizator cmiNCosmin Poieana cmiN Data 14 aprilie 2011 16:30:09
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <cstdio>
#define nxt (*str - 'a')

struct Trie {
    int words, sons;
    Trie* to[26];
    Trie()
    {
        words = sons = 0;
        for (int i = 0; i < 26; i++) {
            to[i] = NULL;
        }
    }
}* root = new Trie;

void add(Trie* node, char* str)
{
    if (!(*str)) {
        node->words++;
    } else {
        if (!node->to[nxt]) {
            node->sons++;
            node->to[nxt] = new Trie;
        }
        add(node->to[nxt], str + 1);
    }
}

bool del(Trie* node, char* str)
{
    if (!(*str)) {
        node->words--;
    } else if (del(node->to[nxt], str + 1)) {
        node->to[nxt] = NULL;
        node->sons--;
    }
    if (!node->sons && !node->words && node != root) {
        return 1;
    } else {
        return 0;
    }
}

int count(Trie* node, char* str)
{
    if (!(*str)) {
        return node->words;
    } else {
        return count(node->to[nxt], str + 1);
    }
}

int prefix(Trie* node, char* str, int nr)
{
    if (!(*str) || !node->to[nxt]) {
        return nr;
    } else {
        return prefix(node->to[nxt], str + 1, nr + 1);
    }
}

int main()
{
    int op;
    char str[32];
    freopen("trie.in", "rt", stdin);
    freopen("trie.out", "wt", stdout);
    while (!feof(stdin)) {
        scanf("%d %s\n", &op, str);
        switch (op) {
        case 0:
            add(root, str);
            break;
        case 1:
            del(root, str);
            break;
        case 2:
            printf("%d\n", count(root, str));
            break;
        case 3:
            printf("%d\n", prefix(root, str, 0));
            break;
        }
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}