Cod sursa(job #1325244)

Utilizator gallexdAlex Gabor gallexd Data 23 ianuarie 2015 16:42:50
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <cstdio>
#include <cstring>

struct Node {
    char letter;
    int counter;
    int wordEnd;
    Node* next[26];
}*Trie;

int cmd;
char word[21];

void add(char *word) {
    Node *p = Trie;
    char c;

    for (int i=0; i<strlen(word); ++i) {
        c = word[i] - 'a';
        if (p->next[c] == NULL)
            p->next[c] = new Node;
        p = p->next[c];
        p->letter = word[i];
        p->counter++;
    }
    p->wordEnd++;
}

void rem(Node *n, char *word) {
    if (*word == NULL)
        return;
    bool del = false;
    if (*(word+1) == NULL)
        n->wordEnd--;
    n->counter--;
    if (n->next[*word - 'a']->counter == 1)
        del = true;
    rem(n->next[*word - 'a'], word+1);
    if (n->counter == 0)
        delete n;
    if (del)
        n->next[*word - 'a'] = NULL;

}

int app(char *word) {
    Node *p = Trie;
    char c;

    for (int i=0; i<strlen(word); ++i) {
        c = word[i] - 'a';
        if (!p->next[c])
            return 0;
        p = p->next[c];
    }
    return p->wordEnd;
}

int prefix(char *word) {
    Node *p = Trie;
    char c;

    for (int i=0; i<strlen(word); ++i) {
        c = word[i] - 'a';
        if (p->next[c] == NULL)
            return i;
        p = p->next[c];
    }
    return strlen(word);
}

int main () {

    freopen("trie.in", "rt", stdin);
    freopen("trie.out", "wt", stdout);

    Trie = new Node;
    while (!feof(stdin)) {
        scanf("%d %s\n", &cmd, word);
        switch (cmd) {
            case 0:
                add(word);
                break;
            case 1:
                rem(Trie, word);
                break;
            case 2:
                printf("%d\n",app(word));
                break;
            case 3:
                printf("%d\n",prefix(word));
                break;
        }
    }

    return 0;
}