Cod sursa(job #2710882)

Utilizator raducostacheRadu Costache raducostache Data 23 februarie 2021 12:01:19
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <cstring>

#define NMAX 1005

using namespace std;

class trie {
public:
    int node, nodepref;
    trie *next[26];

    trie() {
        node = nodepref = 0;
        memset(next, 0, sizeof(next));
    }
};

trie *t = new trie;

void add(trie *, char *, int);
int number(trie *, char *);
int longestPref(trie *, char *, int);

int main() {
    ifstream f("trie.in");
    ofstream g("trie.out");

    int taskId;
    char s[NMAX];

    while (f >> taskId >> s) {
        switch(taskId) {
            case 0: add(t, s, 1); break;
            case 1: add(t, s, -1); break;
            case 2: g << number(t, s) << '\n'; break;
            case 3: g << longestPref(t, s, 0) << '\n'; break;

        }
    }

    return 0;
}

void add(trie *tr, char *s, int change) {
    if (*s == NULL) {
        tr->node += change;
        tr->nodepref += change;
        return;
    }
    tr->nodepref += change;
    if (tr->next[*s - 'a'] == 0)
        tr->next[*s - 'a'] = new trie;
    add(tr->next[*s - 'a'], s + 1, change);
    if (tr->next[*s - 'a']->nodepref == 0)
        delete tr->next[*s - 'a'], tr->next[*s - 'a'] = 0;

}

int number(trie *tr, char *s) {
    if(tr == NULL)
        return 0;
    if(*s == NULL) {
        return tr->node;
    }
    return number(tr->next[*s - 'a'], s + 1);

}
int longestPref(trie *tr, char *s, int pr) {
    if(*s == NULL)
        return pr;
    else if (tr->next[*s - 'a'] == 0)
        return pr;
    return longestPref(tr->next[*s - 'a'], s + 1, pr + 1);
}