Cod sursa(job #636104)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 19 noiembrie 2011 17:02:49
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <cstdio>
#include <cstring>
struct Node {
    int v;
    Node* f[26];
    Node* parent;
    int nrf;
    int ind;
    Node() {
        v = 0;
        nrf = 0;
        parent = 0;
        memset(f, 0, 26 * sizeof(Node*));
    }
};


void insert(Node* p, char* word, int len) {
    if (len == 0) {
        p -> v++;
        return;
    }
    if(p->f[word[0] - 'a'] == 0) {
        p->nrf++;
        p->f[word[0] - 'a'] = new Node();
        p->f[word[0] - 'a']-> parent = p;
        p->f[word[0] - 'a']-> ind = word[0] - 'a';
    }
    insert(p->f[word[0] - 'a'], word + 1, len - 1);

}
void del(Node* p, char* word, int len) {
    if(len == 0) {
        p->v --;
        if(p->v == 0) {
         p -> parent -> nrf--;
         p -> parent -> f[p->ind] = 0;
         delete(p);
        }
        return;
    }
    del(p->f[word[0]- 'a'], word + 1, len - 1);
    if ((p->v == 0) && (p->nrf == 0) && (p->parent != 0)) {
      p -> parent -> nrf--;
      p -> parent -> f[p->ind] = 0;
      delete(p);
    }
}
int search(Node* p, char* word, int len) {
    if(p == 0) return 0;
    if(len == 0) {
        return p -> v;
    }
    return search(p -> f[word[0] - 'a'], word + 1, len - 1);
}
int maxPrefix(Node* p, char* word, int len) {
    if(p == 0) return -1;
    if(len == 0) return 0;
    return 1 + maxPrefix(p->f[word[0] - 'a'], word + 1, len - 1);
}
int main() {

    Node* trie = new Node();
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    while(!feof(stdin)) {
        int n;
        char s[21];
        int u = scanf("%d %s ",&n,&s);
        int l = strlen(s);
        if (u == 0)
         break;
        if (n == 0) {
            insert(trie, s, l);
        }
        else
        if (n == 1) {
            del(trie, s, l);
        }
        else
        if (n == 2) {
            printf("%d\n",search(trie, s, l));
        }
        else {
            printf("%d\n",maxPrefix(trie,s, l));
        }

    }
    return 0;
}