Cod sursa(job #1104822)

Utilizator lorundlorund lorund Data 11 februarie 2014 07:27:52
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <cstdio>
#include <vector>

struct node{
    int cnt, nrfii;
    node *fiu[26];

    node(): cnt(0), nrfii(0), fiu() {}
};

node *root = new node();
int op;
char word[21];

void add(char *word){
    node *p = root;

    for (; *word; ++word){
        if (!p->fiu[*word-'a']){
            p->fiu[*word-'a'] = new node();
            ++p->nrfii;
        }
        p = p->fiu[*word-'a'];
    }
    ++p->cnt;
}

bool del(node *p, char *word){
    if (*word){
        if (del(p->fiu[*word-'a'], word+1)){
            p->fiu[*word-'a'] = 0;
            --p->nrfii;
        }
    }
    else{
        --p->cnt;
    }

    if (!p->cnt && !p->nrfii && p!=root){
        delete p;
        return 1;
    }
    return 0;
}

int numOfAparitions(char *word){
    node *p = root;

    for (; p && *word; ++word){
        p = p->fiu[*word-'a'];
    }
    if (p){
        return p->cnt;
    }
    else{
        return 0;
    }
}

int getLongest(char *word){
    //trebuie sa verific ca daca cuvantul deja e in trie nu longest-1 ci longest
    node *p = root;
    int longest = 0;

    for (; p && *word; ++word){
        p = p->fiu[*word-'a'];
        ++longest;
    }

    if (!p){
        return longest-1;
    }
    else{
        return longest;
    }
}

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

    while (scanf("%d %s", &op, word) != EOF){
        switch (op){
        case 0:
            add(word);
            break;
        case 1:
            del(root, word);
            break;
        case 2:
            printf("%d\n", numOfAparitions(word));
            break;
        case 3:
            printf("%d\n", getLongest(word));
            break;
            break;
        }
    }
    return 0;
}