Pagini recente » Cod sursa (job #3196940) | Cod sursa (job #2296571) | Cod sursa (job #1018829) | Cod sursa (job #2582779) | Cod sursa (job #2949356)
#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;
}