Cod sursa(job #1663502)

Utilizator TopiAlexTopala Alexandru TopiAlex Data 26 martie 2016 08:10:58
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <stdio.h>
#include <string.h>
#define N_MAX 25
#define ALFABET 26
#define CH (*s - 'a')
using namespace std;

struct Nod {
    int nrFii;
    int cnt;
    Nod * fiu[ALFABET];

    Nod () {
        this->cnt = 0;
        this->nrFii = 0;
        memset(fiu, 0, sizeof( fiu ));
    }
};

typedef Nod * Trie;

Trie T = new Nod;

void adauga(Trie, char*);
int sterge(Trie,char*);
int getAparitii (Trie, char*);
int getMaxPrefix (Trie, char*, int);

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

    char line[N_MAX];

    fgets(line, N_MAX-1, stdin);
    while (!feof(stdin)){
        switch (line[0]){
            case '0' : adauga(T, line+2); break;
            case '1' : sterge(T, line+2); break;
            case '2' : printf("%d\n", getAparitii(T, line+2)); break;
            case '3' : printf("%d\n", getMaxPrefix(T, line+2, 0)); break;
        }
        fgets(line, N_MAX-1, stdin);
    }

    return 0;
}

void adauga(Trie nod, char *s){
    if (*s == '\n'){
        nod->cnt++;
        return;
    }

    if (nod->fiu[CH] == NULL){
        nod->fiu[CH] = new Nod;
        nod->nrFii++;
    }
    adauga(nod->fiu[CH], s+1);
}

int sterge(Trie nod, char *s){
    if (*s == '\n'){
        nod->cnt--;
    } else if (sterge(nod->fiu[CH], s+1)) {
        nod->fiu[CH] = NULL;
        nod->nrFii--;
    }

    if (nod != T && nod->nrFii == 0 && nod->cnt == 0){
        delete nod;
        return 1;
    }
    return 0;
}

int getAparitii(Trie nod, char *s){
    if (*s == '\n') return nod->cnt;

    if (nod->fiu[CH] != NULL) return getAparitii(nod->fiu[CH], s+1);

    return 0;
}

int getMaxPrefix(Trie nod, char *s, int k){
    if (*s == '\n') return k;

    if (nod->fiu[CH] != NULL)
        return getMaxPrefix(nod->fiu[CH], s+1, k+1);
    return k;
}