Cod sursa(job #1802626)

Utilizator robx12lnLinca Robert robx12ln Data 10 noiembrie 2016 15:26:27
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include<fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct trie{
    int cnt;
    int fii;
    trie *next[26];

    trie(){
        cnt = fii = 0;
        for( int i = 0; i <= 25; i++ ){
            next[i] = 0;
        }
    }

};
trie *rad;
int op;
char s[25];
void add( trie *nod, char *s ){
    if( *s == 0 ){
        nod->cnt++;
    }else{
        if( nod->next[ *s - 'a' ] == NULL ){
            nod->next[ *s - 'a' ] = new trie;
            nod->fii++;
        }
        add( nod->next[ *s - 'a' ], s + 1 );
    }
}
int det_number( trie *nod, char *s ){
    if( *s == 0 ){
        return nod->cnt;
    }
    if( nod->next[ *s - 'a' ] == NULL ){
        return 0;
    }
    return det_number( nod->next[ *s - 'a' ], s + 1 );
}
int del( trie *&nod, char *s ){
    if( *s == 0 ){
        nod->cnt--;
        if( nod->cnt == 0 && nod->fii == 0 && nod != rad ){
            delete nod;
            nod = 0;
            return 1;
        }else{
            return 0;
        }
    }else{
        if( del( nod->next[ *s - 'a' ], s + 1 ) == 1 ){
            if( nod->cnt == 0 && nod->fii == 0 && nod != rad ){
                delete nod;
                nod = 0;
                return 1;
            }else{
                return 0;
            }
        }
    }
}
int prefmax( trie *nod, char *s ){
    int nr = 0;
    while( *s != 0 && nod->next[ *s - 'a' ] != NULL ){
        nod = nod->next[ *s - 'a' ];
        s++;
        nr++;
    }
    return nr;
}
int main(){
    rad = new trie;
    while( fin >> op >> s ){
        if( op == 0 ){
            add( rad, s );
        }
        if( op == 1 ){
            del( rad, s );
        }
        if( op == 2 ){
            fout << det_number( rad, s ) << "\n";
        }
        if( op == 3 ){
            fout << prefmax( rad, s ) << "\n";
        }
    }
    return 0;
}