Cod sursa(job #2762299)

Utilizator giotoPopescu Ioan gioto Data 6 iulie 2021 13:08:40
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
using namespace std;

struct Trie {
    int nr, pass;
    Trie *sons[26];

    Trie() : nr(0), pass(0) {
        memset(sons, NULL, sizeof(sons));
    };

    void add(const string &s, int h = 0) {
        ++pass;
        if (h == (int)s.size()) {
            ++nr;
            return ;
        }

        if (sons[s[h] - 'a'] == NULL) sons[s[h] - 'a'] = new Trie;
        sons[s[h] - 'a']->add(s, h + 1);
    }

    void remove(const string &s, int h = 0) {
        --pass;
        if (h == (int)s.size()) {
            --nr;
            return ;
        }

        sons[s[h] - 'a']->remove(s, h + 1);
    }

    int cnt(string &s, int h = 0) {
        if (pass == 0) return 0;

        if (h == (int)s.size()) return nr;
        if (sons[s[h] - 'a'] != NULL) return sons[s[h] - 'a']->cnt(s, h + 1);

        return 0;
    }

    int dfs(string &s, int h = 0) {
        if (pass == 0) return 0;

        if (h == (int)s.size()) return h;
        if (sons[s[h] - 'a'] != NULL && sons[s[h] - 'a']->pass != 0) return sons[s[h] - 'a']->dfs(s, h + 1);

        return h;
    }
};


Trie *T;

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

    T = new Trie;

    int tip;
    string s;

    while (fin >> tip >> s) {
        if (tip == 0) T->add(s);
        else if (tip == 1) T->remove(s);
        else if (tip == 2) fout << T->cnt(s) << "\n";
        else if (tip == 3) fout << T->dfs(s) << "\n";
    }

    return 0;
}