Pagini recente » Cod sursa (job #682187) | Cod sursa (job #1318923) | Cod sursa (job #2904634) | Cod sursa (job #831100) | Cod sursa (job #1358274)
#include <fstream>
#include <cstring>
using namespace std;
const int SIGMA = 26;
ifstream is("trie.in");
ofstream os("trie.out");
struct Node{
Node()
{
nr_cuv = nr_sons = 0;
memset ( son, 0, sizeof ( son ) );
}
int nr_cuv, nr_sons;
Node* son[SIGMA];
};
Node *T = new Node;
char sir[SIGMA];
int type;
void Insert(Node *nod, char *s)
{
if( *s == '\0' )
{
nod->nr_cuv++;
return;
}
if( nod->son[*s - 'a'] == 0 )
{
nod->son[*s - 'a'] = new Node;
nod->nr_sons++;
}
Insert(nod->son[*s - 'a'], s+1);
}
bool Delete( Node *nod, char *s )
{
if( !nod )
return false;
if( *s == 0 )
nod->nr_cuv--;
else
if( Delete(nod->son[*s - 'a'], s+1) )
{
nod->son[*s - 'a'] = 0;
nod->nr_sons--;
}
if( nod->nr_cuv == 0 && nod->nr_sons == 0 && nod != T )
{
delete nod;
return true;
}
return false;
}
int Count( Node *nod, char *s )
{
if( *s == '\0' )
return nod->nr_cuv;
if( nod->son[*s - 'a'] )
return Count(nod->son[*s - 'a'], s+1);
return 0;
}
int Prefix( Node *nod, char *s, int k )
{
if( *s == '\0' || nod->son[*s - 'a'] == 0 )
return k;
return Prefix( nod->son[*s - 'a'], s+1, k+1);
}
int main()
{
while( is >> type >> sir )
{
if( type == 0 )
Insert(T, sir);
if( type == 1 )
Delete(T, sir);
if( type == 2 )
os << Count(T, sir) << '\n';
if( type == 3 )
os << Prefix(T, sir, 0) << '\n';
}
is.close();
os.close();
return 0;
}