Cod sursa(job #1527897)

Utilizator depevladVlad Dumitru-Popescu depevlad Data 18 noiembrie 2015 20:22:09
Problema Trie Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <cstdio>
#include <cstring>

using namespace std;

const int SIGMA = 26;
const int MAX_LEN = 20;

struct Node {
    Node* f[SIGMA];
    int path_count;
    int word_count;

    Node() {
        path_count = word_count = 0;
        memset(f, 0, sizeof(f));
    }
};

void wInsert(const char *W, int p, Node* T) {
    if(W[p] == 0) {
        T->word_count++;
    }
    else {
        if(T->f[W[p] - 'a'] == NULL) {
            T->f[W[p] - 'a'] = new Node;
            T->path_count++;
        }
        wInsert(W, p + 1, T->f[W[p] - 'a']);
    }
}

bool wDelete(const char *W, int p, Node *T) {
    if(W[p] == 0) {
        T->word_count--;
    }
    else if(wDelete(W, p + 1, T->f[W[p] - 'a']) == true) {
        T->f[W[p] - 'a'] = NULL;
        T->path_count--;
    }
    if(T->word_count == 0 && T->path_count == 0) {
        delete T;
        return true;
    }
    return false;
}

int wCount(const char *W, int p, Node *T) {
    if(W[p] == 0) {
        return T->word_count;
    }
    else if(T->f[W[p] - 'a'] == NULL) {
        return 0;
    }
    else {
        return wCount(W, p + 1, T->f[W[p] - 'a']);
    }
}

int wLCP(const char *W, int p, Node *T) {
    if(W[p] == 0) {
        return p;
    }
    else if(T->f[W[p] - 'a'] == NULL) {
        return p;
    }
    return wLCP(W, p + 1, T->f[W[p] - 'a']);
}

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

    int t;
    char W[MAX_LEN + 5];
    Node *T = new Node;

    while(scanf("%d %s\n", &t, &W) != EOF) {
        if(t == 0) wInsert(W, 0, T);
        else if(t == 1) wDelete(W, 0, T);
        else if(t == 2) printf("%d\n", wCount(W, 0, T));
        else printf("%d\n", wLCP(W, 0, T));
    }

    return 0;
}