Cod sursa(job #2949356)

Utilizator Fantastic_Mantudor voicu Fantastic_Man Data 30 noiembrie 2022 15:08:34
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>

using namespace std;
const int sigma = 26;

struct trie {
    trie *link[sigma] = {};
    int frecv;
    int pref;
};

void add ( trie *root, char *s ) {
    if ( *s == NULL )
        root->frecv++;
    else {
        if ( root->link[*s - 'a'] == NULL )
            root->link[*s - 'a'] = new trie;
        root->link[*s - 'a']->pref++;
        add ( root->link[*s - 'a'], s + 1 );
    }
}

void del ( trie *root, char *s ) {
    if ( *s == NULL )
        root->frecv--;
    else {
        root->link[*s - 'a']->pref--;
        del ( root->link[*s - 'a'], s + 1 );
    }
}

int freq ( trie *root, char *s ) {
    if ( *s == NULL )
        return root->frecv;
    if ( root->link[*s - 'a'] == NULL )
        return 0;
    return freq ( root->link[*s - 'a'], s + 1 );
}

int lcp ( trie *root, char *s, int len ) {
    if ( *s == NULL )
        return len;
    if ( root->link[*s - 'a'] == NULL || root->link[*s - 'a']->pref == 0 )
        return len;
    return lcp ( root->link[*s - 'a'], s + 1, len + 1 );
}

trie *root = new trie;

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

int main() {
    int tip;
    char s[20];
    while ( fin >> tip >> s ) {
        switch ( tip ) {
            case 0: add ( root, s );
                    break;

            case 1: del ( root, s );
                    break;

            case 2: fout << freq ( root, s ) << '\n';
                    break;

            default: fout << lcp ( root, s, 0 ) << '\n';
        }
    }
    return 0;
}