Pagini recente » Cod sursa (job #1788077) | Cod sursa (job #1829052) | Cod sursa (job #409669) | Cod sursa (job #2763849) | Cod sursa (job #2230057)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
class TRIE
{
public:
TRIE *letter[28];
int apparitions;
TRIE ()
{
for ( int i = 0; i <= 26; ++i )
letter[i] = nullptr;
apparitions = 0;
}
};
TRIE *root;
void insertWord ( string word )
{
TRIE *current_Root = root;
current_Root->apparitions++;
for ( auto x : word )
{
int current_Position = x-'a';
if ( current_Root->letter[current_Position] == nullptr )
current_Root->letter[current_Position] = new TRIE();
current_Root = current_Root->letter[current_Position];
current_Root->apparitions++;
}
}
void eraseWord ( string word )
{
TRIE *current_Root = root;
current_Root->apparitions--;
for ( auto x : word )
{
int current_Position = x-'a';
current_Root = current_Root->letter[current_Position];
current_Root->apparitions--;
if ( current_Root->apparitions == 0 )
current_Root->letter[current_Position] = nullptr;
}
}
int countApparitionsOf ( string word )
{
TRIE *current_Root = root;
for ( auto x:word )
{
int current_Position = x-'a';
if ( current_Root->letter[current_Position] == nullptr )
return 0;
current_Root = current_Root->letter[current_Position];
}
int different_Words = 0;
for ( int i = 0; i < 26; ++i )
{
if ( current_Root->letter[i] != nullptr )
different_Words += current_Root->letter[i]->apparitions;
}
return current_Root->apparitions-different_Words;
}
int countLongestPreffix( string word )
{
TRIE *current_Root = root;
int length_of_Preffix = 0;
for ( auto x:word )
{
int current_Position = x-'a';
if ( current_Root->letter[current_Position] == nullptr || current_Root->letter[current_Position]->apparitions == 0 )
return length_of_Preffix;
length_of_Preffix++;
current_Root = current_Root->letter[current_Position];
}
return length_of_Preffix;
}
int main()
{
root = new TRIE();
int type;
string word;
while ( fin>>type )
{
fin>>word;
if ( type == 0 )
insertWord(word);
if ( type == 1 )
eraseWord(word);
if ( type == 2 )
fout<<countApparitionsOf(word)<<'\n';
if ( type == 3 )
fout<<countLongestPreffix(word)<<'\n';
}
}