Pagini recente » Cod sursa (job #2731368) | Cod sursa (job #443527) | Cod sursa (job #2669168) | Cod sursa (job #1570884) | Cod sursa (job #1260341)
#include <fstream>
using namespace std;
ifstream is("trie.in");
ofstream os("trie.out");
struct Trie {
int countSons;
int countWords;
Trie *actualSon[26];
Trie()
{
countSons = 0;
countWords = 0;
for ( int i = 0; i < 26; ++i )
actualSon[i] = 0;
}
}; Trie *T = new Trie;
void addWord(Trie *x, char *s );
bool deleteWord(Trie *x, char *s);
void countApparitions(Trie *x, char *s);
int preffixLength(Trie *x, char *s, int length);
int Q, type, NrAP;
char A[21];
int main()
{
while ( is >> type)
{
is >> A;
switch(type)
{
case 0:
addWord(T,A);
break;
case 1:
deleteWord(T,A);
break;
case 2:
NrAP = 0;
countApparitions(T,A);
os << NrAP << '\n';
break;
case 3:
os << preffixLength(T,A,0) << '\n';
break;
}
}
is.close();
os.close();
}
void addWord(Trie *x, char *s)
{
if ( s[0] == NULL )
{
x->countWords++;
return;
}
if ( x->actualSon[s[0] - 'a'] == 0 )
{
x->countSons++;
x->actualSon[s[0] - 'a'] = new Trie;
}
addWord(x->actualSon[s[0] - 'a'], s + 1);
}
bool deleteWord(Trie *x, char *s)
{
if ( s[0] == NULL )
x->countWords--;
if ( s[0] != NULL )
{
if ( deleteWord(x->actualSon[s[0] - 'a'], s + 1 ) )
{
x->countSons--;
x->actualSon[s[0] - 'a'] = 0;
}
}
if ( x->countWords == 0 && x->countSons == 0 && x != T )
{
delete x;
return 1;
}
else
return 0;
}
void countApparitions(Trie *x, char *s)
{
if ( s[0] == NULL )
{
NrAP += x->countWords;
return;
}
else
{
if ( x->actualSon[s[0] - 'a'] != 0)
countApparitions(x->actualSon[s[0] - 'a'],s + 1);
}
}
int preffixLength(Trie *x, char *s,int length)
{
if ( s[0] == NULL || x->actualSon[s[0] - 'a'] == 0 )
return length;
else
return preffixLength(x->actualSon[s[0] - 'a'], s + 1, length + 1);
}