Cod sursa(job #2486633)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 3 noiembrie 2019 11:40:22
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.71 kb

#include <fstream>
#include <cstring>
using namespace std;
ifstream in ( "trie.in" );
ofstream out ( "trie.out" );
struct nod {
    int info;
    nod *urm[26], *prec[26];
    /*nod() {
        info = 0;
        memset ( urm, 0, sizeof ( urm ) );
        memset ( prec, 0, sizeof ( prec ) );
    }*/
};
nod* prim;
void adaug ( nod* &first, string s ) {
    if ( first == NULL ) {
        first = new nod;
        first->info = 0;
        for ( int i = 0; i < 26; i++ )
            first->prec[i] = first->urm[i] = NULL;
    }
    nod *aux = first;
    for ( int i = 0; i < s.size(); i++ ) {
        if ( aux->urm[s[i] - 'a'] == NULL ) {
            nod *aux2 = new nod;
            aux->urm[s[i] - 'a'] = aux2;
            if ( i != 0 )
                aux2->prec[s[i - 1] - 'a'] = aux;
            aux = aux2;
            for ( int j = i + 1; j < s.size(); j++ ) {
                aux2 = new nod;
                aux2->info = 0;
                for ( int k = 0; k < 26; k++ )
                    aux2->urm[k] = aux2->prec[k] = NULL;
                aux->urm[s[j] - 'a'] = aux2;
                aux2->prec[s[j - 1] - 'a'] = aux;
                aux = aux2;
            }
            break;
        } else
            aux = aux->urm[s[i] - 'a'];
    }
        aux->info++;
}
void scoate ( nod* &first, string s ) {
    nod *aux = first;
    for ( int i = 0; i < s.size(); i++ )
        aux = aux->urm[s[i] - 'a'];
    if ( aux->info >= 2 )
        aux->info--;
    else {
        aux->info--;
        nod *aux2;
        for ( int i = s.size() - 1; i >= 0 && !aux->info; i-- ) {
            if ( i != 0 )
                aux2 = aux->prec[s[i - 1] - 'a'];
            else
                aux2 = first;
            aux2->urm[s[i] - 'a'] = NULL;
            delete ( aux );
            aux = aux2;
        }
    }
}
void afiseaza ( nod* &first, string s ) {
    nod *aux = first;
    for ( int i = 0; i < s.size(); i++ )
        aux = aux->urm[s[i] - 'a'];
    out << aux->info << '\n';
}
void prefix ( nod* &first, string s ) {
    nod *aux = first;
    int max1 = 0, cnt = 0;
    for ( int i = 0; i < s.size() && aux != NULL; i++ ) {
        aux = aux->urm[s[i] - 'a'];
        cnt++;
        if ( aux != NULL && aux->info )
            max1 = cnt;
    }
    out << max1 << '\n';
}
string s, s0;
int main() {
    int t;
    in >> t >> ws >> s;
    //prim = new nod();
    while ( s != s0 ) {
        if ( t == 0 )
            adaug ( prim, s );
        else if ( t == 1 )
            scoate ( prim, s );
        else if ( t == 2 )
            afiseaza ( prim, s );
        else
            prefix ( prim, s );
        s0 = s;
        in >> t >> ws >> s;
    }
    return 0;
}