Cod sursa(job #2921183)

Utilizator AztecaVlad Tutunaru 2 Azteca Data 28 august 2022 10:57:30
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>

using namespace std;

const int SIGMA = 26;

struct Trie {
    Trie *sons[SIGMA];
    int freq;
    int words;

    Trie() {
        freq = 0;
        words = 0;
        for (int i = 0; i < SIGMA; i++) {
            sons[i] = NULL;
        }
    }
};

void ins(Trie *&root, char *S) {
    if (*S == '\0') {
        root->freq++;
        root->words++;
    } else {
        if (root->sons[S[0] - 'a'] == NULL) {
            root->sons[S[0] - 'a'] = new Trie();
        }
        root->sons[S[0] - 'a']->freq++;
        ins(root->sons[S[0] - 'a'], S + 1);
    }
}

void del(Trie *&root, char *S) {
    if (*S == '\0') {
        if (root->freq > 0) {
            root->freq--;
            root->words--;
        }
    } else {
        if (root->sons[S[0] - 'a'] != NULL) {
            root->sons[S[0] - 'a']->freq--;
            del(root->sons[S[0] - 'a'], S + 1);
        }
    }
}

int cntocc(Trie *&root, char *S) {
    if (*S == '\0') {
        return root->words;
    } else {
        if (root->sons[S[0] - 'a'] == NULL || root->sons[S[0] - 'a']->freq == 0) {
            return 0;
        }
        return cntocc(root->sons[S[0] - 'a'], S + 1);
    }
}

int maxpref(Trie *&root, char *S, int cnt = 0) {
    if (*S == '\0') {
        return cnt;
    } else {
        if (root->sons[S[0] - 'a'] != NULL && root->sons[S[0] - 'a']->freq != 0) {
            return maxpref(root->sons[S[0] - 'a'], S + 1, cnt + 1);
        } else {
            return cnt;
        }
    }
}

int main() {
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    int t;
    Trie *root = new Trie();
    while (fin >> t) {
        char* S = new char[20 + 1];
        fin >> S;
        if (t == 0) {
            ins(root, S);
        } else if (t == 1) {
            del(root, S);
        } else if (t == 2) {
            fout << cntocc(root, S) << "\n";
        } else {
            fout << maxpref(root, S) << "\n";
        }
    }
    return 0;
}