Cod sursa(job #2877099)

Utilizator WilIiamperWilliam Damian Balint WilIiamper Data 24 martie 2022 09:38:45
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <fstream>
#include <iostream>
#include <cassert>

using namespace std;

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

struct Trie {
    int cnt, sons;
    Trie * fiu[26];

    Trie() {
        cnt = 0; sons = 0;
        for ( int i = 0; i < 26; i++ )
            fiu[i] = nullptr;
    }
};

Trie T[1];

int pref ( Trie * node, char * word, int k ) {
    //cout << k << " " << char((*word)) << "\n";
    if ( *word == '\n' || *word == '\0' || !node->fiu[ *word - 'a' ] )
        return k;

    pref( node->fiu[ *word-'a' ], word+1, k+1 );
}

int query ( Trie * node, char * word ) {
    //cout << node->cnt << " " << char((*word)) << "\n";
    if ( *word == '\n' || *word == '\0' )
        return node->cnt;

    int i = (*word) - 'a';
    if ( node->fiu[i] )
        return query( node->fiu[i], word+1 );
    return 0;
}

bool delWord ( Trie * node, char * word ) {
    if ( *word == '\n' || *word == '\0' ) {
        node->cnt--;
    } else if ( delWord( node->fiu[ *word - 'a' ], word+1 ) ){
        node->fiu[ *word-'a' ] = nullptr;
        //assert ( !node->fiu[ *word-'a' ] );
        node->sons--;
    }

    if ( !node->sons && !node->cnt && node != T ) {
        delete node;
        return true;
    }

    return false;
}

void addWord( Trie * node, char * word ) {
    if ( *word == '\n' || *word == '\0' ) {
        node->cnt++;
        return;
    }

    int i = (*word) - 'a';
    if ( node->fiu[ i ] == 0 ) {
        node->fiu[i] = new Trie;
        node->sons++;
    }

    addWord( node->fiu[i], word+1 );
}

int main () {
    char line[ 25 ];

    while ( fin.getline( line, 24 ) ) {
        switch ( line[0] ) {
            case '0': {
                addWord( T, line + 2 );
                break;
            }
            case '1': {
                delWord( T, line+2 );
                break;
            }
            case '2': {
                 fout << query( T, line + 2 ) << "\n";
                break;
            }
            case '3': {
                 fout << pref( T, line + 2, 0 ) << "\n";
                break;
            }
            default: break;
        }
    }
    return 0;
}