Pagini recente » Cod sursa (job #1160276) | Cod sursa (job #642500) | Cod sursa (job #63010) | Cod sursa (job #1624204) | Cod sursa (job #615144)
Cod sursa(job #615144)
#include <cstdio>
#include <cstring>
#define LMAX 30
using namespace std;
struct nod
{
nod *L[26];
int CateCuv, CatiFii;
nod()
{
memset( L, 0, sizeof(L) );
CateCuv = CatiFii = 0;
}
};
nod *R;
int Tip, LC;
char Cuv[LMAX];
inline void Adauga( nod *NOD, char *lit )
{
if( *lit == '\n' )
{
++(NOD -> CateCuv);
return;
}
if( !(NOD -> L[*lit - 'a']) )
{
NOD -> L[*lit - 'a'] = new nod;
++(NOD -> CatiFii);
}
Adauga( NOD -> L[*lit - 'a'], lit+1 );
}
inline int Scoate( nod *NOD, char *lit )
{
if( *lit == '\n' ) --(NOD -> CateCuv);
else if( Scoate( NOD -> L[*lit - 'a'], lit+1 ) )
{
NOD -> L[*lit - 'a'] = 0;
--(NOD -> CatiFii);
}
if( !(NOD -> CateCuv) && !(NOD -> CatiFii) && NOD != R )
{
delete NOD;
return 1;
}
return 0;
}
inline int NrAparitii( nod *NOD, char *lit )
{
if( *lit == '\n' ) return NOD -> CateCuv;
if( NOD -> L[*lit - 'a'] ) return NrAparitii( NOD -> L[*lit - 'a'], lit+1 );
return 0;
}
inline int LGLCP( nod *NOD, char *lit, int Lg )
{
if( *lit == '\n' || !(NOD -> L[*lit - 'a']) ) return Lg;
return LGLCP( NOD -> L[*lit - 'a'], lit+1, Lg+1 );
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
nod *R = new nod;
while( fgets( Cuv, LMAX, stdin ) )
switch( Cuv[0] )
{
case '0':
Adauga( R, Cuv+2 );
break;
case '1':
Scoate( R, Cuv+2 );
break;
case '2':
printf("%d\n", NrAparitii( R, Cuv+2 ));
break;
case '3':
printf("%d\n", LGLCP( R, Cuv+2, 0 ));
break;
}
return 0;
}