Cod sursa(job #3207594)

Utilizator raresgherasaRares Gherasa raresgherasa Data 26 februarie 2024 15:53:09
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("trie.in");
ofstream fout ("trie.out");

struct Trie {
    Trie *sons[26];
    int cnt = 0, prefix = 0;
    Trie() {
        cnt = 0;
        prefix = 0;
        memset(sons, 0, sizeof(sons));
    }
};

Trie *root = new Trie;

void add (Trie *root, char s[]) {
    if (s[0] == NULL) {
        ++root -> cnt;
    } else {
        if (root -> sons[s[0] - 'a'] == NULL) {
            root -> sons[s[0] - 'a'] = new Trie();
        }
        ++root -> sons[s[0] - 'a'] -> prefix;
        add(root -> sons[s[0] - 'a'], s + 1);
    }
}

void del (Trie *root, char s[]) {
    if (s[0] == NULL) {
        --root -> cnt;
    } else {
        --root -> sons[s[0] - 'a'] -> prefix;
        del(root -> sons[s[0] - 'a'], s + 1);
    }
}

int countAparitii (Trie *root, char s[]) {
    if (s[0] == 0) {
        return root -> cnt;
    } else {
        if (root -> sons[s[0] - 'a'] == NULL) {
            return 0;
        }
        return (countAparitii(root -> sons[s[0] - 'a'], s + 1));
    }
}

int longestPrefix (Trie *root, char s[], int k) {
    if (s[0] == 0) {
        return (root -> cnt > 0 ? k : 0);
    } else {
        if (root -> sons[s[0] - 'a'] == NULL || root -> sons[s[0] - 'a'] -> prefix == 0) {
            return 0;
        }
        int a = ((root -> prefix != 0) ? k : 0);
        return max(longestPrefix(root -> sons[s[0] - 'a'], s + 1, k + 1), a);
    }
}

int main() {
    int op;
    char s[21];
    while (fin >> op >> s) {
        if (op == 0) {
            add(root, s);
        } else if (op == 1) {
            del(root, s);
        } else if (op == 2) {
            fout << countAparitii(root, s) << '\n';
        } else if (op == 3) {
            fout << 1 + longestPrefix(root, s, 0) << '\n';
        }
    }
}