Cod sursa(job #673894)

Utilizator ViksenVictor-Nicolae Savu Viksen Data 5 februarie 2012 07:13:05
Problema Trie Scor 15
Compilator c Status done
Runda Arhiva educationala Marime 1.88 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Trie *Trie;
struct Trie {
    Trie next[26];
    unsigned int cnt;
    unsigned int cut;
};

Trie newTrie()
{
    Trie t = malloc(sizeof (struct Trie));
    memset(t, 0, sizeof (struct Trie));
    return t;
}

void deleteTrie(Trie *t)
{
    if (!t) return;
    if (!(*t)) return;
    Trie *end = (*t)->next + 26;
    Trie *p = (*t)->next;
    while (p != end) deleteTrie(p);
    *t = 0;
}

void addWord(Trie *t, const char *w)
{
    if (!w || !t) return;
    if (!(*t)) *t = newTrie();
    if (*w) {
        addWord(&(*t)->next[(*w) - 'a'], w+1);
        ++(*t)->cut;
    } else {
        ++(*t)->cnt;
    }
}

void delWord(Trie *t, const char *w)
{
    if (!w || !t) return;
    if (!(*t)) return;
    if (*w) {
        delWord(&(*t)->next[(*w) - 'a'], w+1);
        --(*t)->cut;
    } else {
        --(*t)->cnt;
    }
}

unsigned int countWord(Trie t, const char *w)
{
    if (!w || !t) return 0;
    if (!(*w)) return t->cnt;
    return countWord(t->next[(*w) - 'a'], w+1);
}

unsigned int matchWord(Trie t, const char *w)
{
    if (!w || !t || !(*w)) return 0;
    if (!t->next[(*w) - 'a']) return 0;
    if (t->cut < 2) return 0;
    return 1 + matchWord(t->next[(*w) - 'a'], w+1);
}

int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    char w[22];
    char o;
    Trie t = 0;
    while (scanf("%c %s\n", &o, w) == 2) {
        switch (o) {
            case '0':
                addWord(&t, w);
                break;
            case '1':
                delWord(&t, w);
                break;
            case '2':
                printf("%u\n", countWord(t, w));
                break;
            case '3':
                printf("%u\n", matchWord(t, w));
                break;
            default:
                break;
        }
    }

    fclose(stdin);
    fclose(stdout);

    return 0;
}