Pagini recente » Cod sursa (job #1649184) | Cod sursa (job #990183) | Cod sursa (job #1079028) | Cod sursa (job #1730207) | Cod sursa (job #2885619)
#include <iostream>
#include <fstream>
using namespace std;
const int SIGMA = 26;
const int MAX_SIZE = 20;
const char FIRST = 'a';
const int BOS = 0;
char input[1 + MAX_SIZE];
struct trie {
int frecv_word, prefix;
trie* children[SIGMA];
trie () {
frecv_word = prefix = 0;
for ( int letter = 0; letter < SIGMA; letter ++ )
children[letter] = NULL;
}
};
void add_to ( trie* root, char* my_string ) {
if ( *my_string != NULL ) {
if ( root -> children[*my_string - FIRST] == NULL )
root -> children[*my_string - FIRST] = new trie;
root = root -> children[*my_string - FIRST];
root -> prefix ++; add_to ( root, my_string + 1 );
}
else
root -> frecv_word ++;
}
void delete_at ( trie* root, char* my_string ) {
if ( *my_string != NULL ) {
root = root -> children[*my_string - FIRST];
root -> prefix --;
delete_at ( root, my_string + 1 );
}
else
root -> frecv_word --;
}
int count_in ( trie* root, char* my_string ) {
if ( *my_string == NULL )
return root -> frecv_word;
if ( root -> children[*my_string - FIRST] == NULL )
return 0;
if ( root -> children[*my_string - FIRST] -> prefix == 0 )
return 0;
return count_in ( root -> children[*my_string - FIRST], my_string + 1 );
}
int LCP ( trie* root, char *my_string, int steps ) {
if ( root -> children[*my_string - FIRST] == NULL )
return steps;
if ( root -> children[*my_string - FIRST] -> prefix == 0 )
return steps;
return LCP ( root -> children[*my_string - FIRST], my_string + 1, steps + 1 );
}
ifstream fin ( "trie.in" );
ofstream fout ( "trie.out" );
int main()
{
trie* root = new trie;
int op;
while ( fin >> op >> input ) {
switch ( op ) {
case 0:
add_to ( root, input );
break;
case 1:
delete_at ( root, input );
break;
case 2:
fout << count_in ( root, input ) << "\n";
break;
case 3:
fout << LCP ( root, input, BOS ) << "\n";
break;
}
}
return 0;
}