Cod sursa(job #2890724)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 16 aprilie 2022 13:42:53
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

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

struct Trie {
    Trie *son[26];
    int prefix;
    int finish;

    Trie() {
        prefix = 0;
        finish = 0;
        for (int i = 0; i < 26; i++) {
            son[i] = NULL;
        }
    }
};

void add(Trie *root, string w) {
    for (int i = 0; i < w.size(); i++) {
        root->prefix++;
        if (root->son[w[i] - 'a'] == NULL) {
            root->son[w[i] - 'a'] = new Trie();
        }
        root = root->son[w[i] - 'a'];
    }
    root->finish++;
    root->prefix++;
}

void erase(Trie *root, string w) {
    for (int i = 0; i < w.size(); i++) {
        root->prefix--;
        root = root->son[w[i] - 'a'];
    }
    root->finish--;
    root->prefix--;
}

int count(Trie *root, string w) {
    for (int i = 0; i < w.size(); i++) {
        if (root->son[w[i] - 'a'] == NULL) {
            return 0;
        }
        root = root->son[w[i] - 'a'];
    }
    return root->finish;
}

int lcp(Trie *root, string w) {
    int depth = 0;
    for (int i = 0; i < w.size(); i++) {
        if (root->son[w[i] - 'a'] == NULL) {
            return depth;
        }
        if (root->son[w[i] - 'a']->prefix == 0) {
            return depth;
        }
        root = root->son[w[i] - 'a'];
        depth++;
    }
    return depth;
}

int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);

    int type;
    string cuv;

    Trie *root = new Trie();

    while (fin >> type >> cuv) {
        if (type == 0) {
            add(root, cuv);
        } else if (type == 1) {
            erase(root, cuv);
        } else if (type == 2) {
            fout << count(root, cuv) << '\n';
        } else {
            fout << lcp(root, cuv) << '\n';
        }
    }

    return 0;
}