Cod sursa(job #2904355)

Utilizator AlexNicuNicu Alexandru AlexNicu Data 17 mai 2022 23:22:33
Problema Trie Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <fstream>
#include <unordered_map>

using namespace std;

ifstream cin ( "trie.in" );
ofstream cout ( "trie.out") ;

struct Trie {
    unordered_map<char, Trie*> nodes;
    int isFinal;
    int words_now;

    Trie* getNode ( char ch ) {
        auto it = nodes.find(ch);
        if ( it != nodes.end() ) {
            return it->second;
        }
        return NULL;
    }

    Trie* addNode ( char ch ) {
        nodes[ch] = new Trie();
        return nodes[ch];
    }

};

Trie root;

void addString ( const string& s ) {
    int i;
    Trie* aux;
    aux = &root;
    for ( i = 0; i < s.size(); ++i ) {
        if ((*aux).getNode(s[i]) == NULL) {
            aux = (*aux).addNode(s[i]);
            (*aux).words_now++;
        }
        else {
            (*aux).words_now++;
            aux = (*aux).getNode(s[i]);
        }
    }
    (*aux).isFinal++;
}

int String_Occurences ( const string& s ) {
    int i;
    Trie* aux;
    aux = &root;
    for ( i = 0; i < s.size(); ++i ) {
        if ((*aux).getNode(s[i]) == NULL) {
            return 0;
        }
        else {
            aux = (*aux).getNode(s[i]);
        }
    }
    return (*aux).isFinal;
}

int Max_Prefix ( const string& s ) {
    int i, cnt;
    Trie* aux;
    aux = &root;
    cnt = 0;
    for ( i = 0; i < s.size(); ++i ) {
        if ((*aux).getNode(s[i]) == NULL) {
            return cnt;
        }
        else {
            cnt += ( (*aux).words_now > 0 );
            aux = (*aux).getNode(s[i]);
        }
    }
}

void Delete_String ( const string& s ) {
    int i;
    Trie* aux;
    aux = &root;
    for ( i = 0; i < s.size(); ++i ) {
        (*aux).words_now--;
        aux = (*aux).getNode(s[i]);
    }
    (*aux).isFinal--;
}

void Evaluate( int op, const string& s ) {
    if ( op == 0 ) {
        addString( s );
    }
    else if ( op == 1 ) {
        Delete_String( s );
    }
    else if ( op == 2 ) {
        cout << String_Occurences( s ) << "\n";
    }
    else if ( op == 3 ) {
        cout << Max_Prefix( s ) << "\n";
    }
}

int main() {
    int op;
    string s;
    while ( cin >> op ) {
        cin >> s;
        Evaluate( op, s );
    }
    return 0;
}