Cod sursa(job #2605278)

Utilizator MocalinnoMoca Andrei Catalin Mocalinno Data 24 aprilie 2020 18:12:33
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h>
#define DAU  ios::sync_with_stdio(false); fin.tie(0); fout.tie(0);
#define PLEC fin.close(); fout.close(); return 0;
using namespace std;
const string problem("trie");
ifstream fin(problem + ".in");
ofstream fout(problem + ".out");

class Trie {
public :
    Trie() : cntsons(0), freq(0) {
        memset(sons, 0, sizeof(sons));
    }
    inline void Add(const string& s, int ind = 0) {
        int x = s[ind] - 'a';
        if (!sons[x]) {
            ++cntsons;
            sons[x] = new Trie;
        }
        if (ind == s.size() - 1)
            ++sons[x] -> freq;
        else sons[x] -> Add(s, ind + 1);
    }

    inline void Erase(const string& s, int ind = 0) {
        int x = s[ind] - 'a';
        if (ind == s.size() - 1)
            --sons[x] -> freq;
        else sons[x] -> Erase(s, ind + 1);

        if (sons[x] -> cntsons == 0 && sons[x] -> freq == 0) {
            delete sons[x];
            sons[x] = 0;
            --cntsons;
        }
    }

    inline int Count(const string& s, int ind = 0) {
        int x = s[ind] - 'a';
        if (sons[x]) {
            if (ind == s.size() - 1)
                return sons[x] -> freq;
            else return sons[x] -> Count(s, ind + 1);
        }
        else return 0;
    }

    inline int LongestPrefix(const string& s, int ind = 0) {
        int x = s[ind] - 'a';
        if (sons[x] && ind < s.size())
            return sons[x] -> LongestPrefix(s, ind + 1);
        else return ind;
    }
private:
    int cntsons, freq;
    Trie* sons[26];
};

Trie *root = new Trie;
int op;
string s;
int main() {
    DAU
    while (fin >> op >> s) {
        if (op == 0)
            root -> Add(s);
        else if (op == 1)
            root -> Erase(s);
        else if (op == 2)
            fout << root -> Count(s) << '\n';
        else fout << root -> LongestPrefix(s) << '\n';
    }
    PLEC
}