Cod sursa(job #2905707)

Utilizator andrei_marciucMarciuc Andrei andrei_marciuc Data 23 mai 2022 10:29:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <stdio.h>
 
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
 
#define DELTA 1e-9
#define MAX 300
 
    
#define SIGMA 26
 
struct Trie {
    int freq;
    int words;
    Trie* children[ SIGMA ];
 
    Trie() {
        freq = 0;
        words = 0;
        for( int i = 0; i < SIGMA; i++ )
            children[ i ] = nullptr;
    }
};
 
void insert( Trie* root, char* S ) {
    if( *S == '\0' ) {
        root->freq++;
        root->words++;
    } else {
        if( root->children[ *S - 'a' ] == nullptr ) 
            root->children[ *S - 'a' ] = new Trie();
        root->children[ *S - 'a' ]->freq++;
        insert(root->children[ *S - 'a' ], S + 1 );
    }
}
 
void erese( Trie* root, char* S ) {
    if( *S == '\0' ) {
        root->freq--;
        root->words--;
    } else {
        if( root->children[ *S - 'a' ] == nullptr ) 
            root->children[ *S - 'a' ] = new Trie();
        root->children[ *S - 'a' ]->freq--;
        erese( root->children[ *S - 'a' ], S + 1 );
    }
}
 
int no( Trie* root, char* S ) {
    if( *S == '\0' )
        return root->words;
    else {
        if( root->children[ *S - 'a' ] == nullptr || root->children[ *S - 'a' ]->freq == 0 )
            return 0;
        return no( root->children[ *S - 'a' ], S + 1 );
    }
}
 
int val;
int rez( Trie* root, char* S ) {
    if( *S == '\0' )
        return val;
    else {
        if( root->children[ *S - 'a' ] == nullptr || root->children[ *S - 'a' ]->freq == 0 )
            return val;
        ++val;
        return rez( root->children[ *S - 'a' ], S + 1 );
    }
}
 
int main()
{
    Trie root;
    int cerinta;
    char s[ 23 ];
    FILE *fin = fopen( "trie.in", "r" );
    FILE *fout = fopen( "trie.out", "w" );
    while( ~fscanf( fin, "%d %s\n", &cerinta, s ) ) {
        if( cerinta == 0 )
            insert( &root, s );
        else if( cerinta == 1 )
            erese( &root, s );
        else if( cerinta == 2 )
            fprintf( fout, "%d\n", no( &root, s ) );
        else {
            val = 0;
            fprintf( fout, "%d\n", rez( &root, s ) );
        }
    }
    fclose( fin );
    fclose( fout );
    return 0;
}