Cod sursa(job #2567152)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 3 martie 2020 15:31:16
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>

using namespace std;

const int LITMAX = 21;

struct Trie {
    int nwords, fr;
    Trie* son[LITMAX];

    Trie() {
        nwords = fr = 0;
        for(int i = 0; i < LITMAX; i ++)
            son[i] = NULL;
    }
};

void addTrie(string &s, int pos, Trie* root) {
    root -> nwords ++;
    if(pos == s.size()) {
        root -> fr ++;
        return;
    }

    int c = s[pos] - 'a';
    if(root -> son[c] == NULL)
        root -> son[c] = new Trie();
    addTrie(s, pos + 1, root -> son[c]);
}

void delTrie(string &s, int pos, Trie* root) {
    root -> nwords --;
    if(pos == s.size()) {
        root -> fr --;
        return;
    }

    int c = s[pos] - 'a';
    delTrie(s, pos + 1, root -> son[c]);
}

int freq(string &s, int pos, Trie* root) {
    if(pos == s.size())
        return root -> fr;

    int c = s[pos] - 'a';
    if(root -> son[c] == NULL)
        return 0;
    return freq(s, pos + 1, root -> son[c]);
}

int prefix(string &s, int pos, Trie* root) {
    if(pos == s.size())
        return 0;

    int c = s[pos] - 'a';
    if(root -> son[c] == NULL)
        return 0;
    if(root -> son[c] -> nwords == 0)
        return 0;
    return (1 + prefix(s, pos + 1, root -> son[c]));
}

Trie* root;

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

    root = new Trie();
    int tip;
    string s;
    while(in >> tip >> s) {
        if(tip == 0)
            addTrie(s, 0, root);
        if(tip == 1)
            delTrie(s, 0, root);
        if(tip == 2)
            out << freq(s, 0, root) << "\n";
        if(tip == 3)
            out << prefix(s, 0, root) << "\n";
    }

    return 0;
}