Pagini recente » Cod sursa (job #1325332) | Cod sursa (job #547801) | Cod sursa (job #2895174) | Cod sursa (job #2869340) | Cod sursa (job #2820926)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int TOTAL_LEN = 1e5;
const int SIGMA = 26;
const int ROOT = 0;
struct TRIE {
struct node {
int link[SIGMA];
int frecv, count_word;
} ds[1 + TOTAL_LEN * SIGMA];
int node_index = 0;
void add_string ( string elem ) {
int node = ROOT;
for ( auto letter : elem ) {
int code = letter - 'a';
if ( !ds[node].link[code] )
ds[node].link[code] = ++ node_index;
node = ds[node].link[code];
ds[node].frecv ++;
}
ds[node].count_word ++;
}
void delete_string ( string elem ) {
int node = ROOT;
for ( auto letter : elem ) {
int code = letter - 'a';
node = ds[node].link[code];
ds[node].frecv --;
}
ds[node].count_word --;
}
int count_app ( string target ) {
int node = ROOT;
auto letter = target.begin (); int code = *letter - 'a';
int next_node = ds[node].link[code];
while ( letter != target.end () && ds[next_node].frecv ) {
node = next_node;
letter ++; code = *letter - 'a';
next_node = ds[next_node].link[code];
}
if ( letter == target.end () )
return ds[node].count_word;
return 0;
}
int longest_common_pref ( string prefix ) {
int result = 0;
int node = ROOT;
auto letter = prefix.begin (); int code = *letter - 'a';
int next_node = ds[node].link[code];
while ( letter != prefix.end () && ds[next_node].frecv ) {
node = next_node;
letter ++; code = *letter - 'a';
next_node = ds[next_node].link[code];
result ++;
}
return result;
}
} trie;
ifstream fin ( "trie.in" );
ofstream fout ( "trie.out" );
int main()
{
int t; string input;
while ( fin >> t >> input ) {
if ( t == 0 )
trie.add_string ( input );
else if ( t == 1 )
trie.delete_string ( input );
else if ( t == 2 ) {
fout << trie.count_app ( input );
fout << "\n";
}
else {
fout << trie.longest_common_pref ( input );
fout << "\n";
}
}
return 0;
}