Pagini recente » Cod sursa (job #2817339) | Cod sursa (job #406178) | Cod sursa (job #2067352) | Cod sursa (job #414865)
Cod sursa(job #414865)
#include <stdio.h>
#define maxn 300000
int trie[300000][26];
int nr[300000];
int nr2[ maxn];
int nr_nodes, rez;
void add( char *sir, int where, int how_muci)
{
//nr[ where] += how_muci;
nr2[ where] += how_muci;
if( sir[0] > 'z' || sir[0] < 'a') {nr[ where] += how_muci;return;}
if( trie[ where ][ sir[0] - 'a' ] == -1)
{
trie[ where ][ sir[0] - 'a' ] = ++nr_nodes;
}
add( sir + 1, trie[ where ][ sir[0] - 'a' ], how_muci);
}
int cate( char *sir, int where)
{
if( sir[0] > 'z' || sir[0] < 'a') return nr[ where];
if( trie[ where ][ sir[0] - 'a' ] == -1)
{
return 0;
}
return cate( sir + 1, trie[ where ][ sir[0] - 'a' ]);
}
int pref( char *sir, int where, int sol)
{
if( nr2[where ] == 0)
{
if( sol != 0)
return sol-1;
return 0;
}
if( trie[ where ][ sir[0] - 'a' ] == -1)
return sol;
if( nr2[where ] == nr2[trie[ where ][ sir[0] - 'a' ]] )
return sol;
return pref( sir + 1, trie[ where ][ sir[0] - 'a' ], sol + 1);
}
int main()
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
char sir[1000];
int n;
for( int i = 0; i < maxn; ++i)
for( int j = 0; j < 26; ++j)
trie[i][j] = -1;
while( scanf("%d %s",&n, sir) == 2)
{
if( n == 0)
add( sir, 0, 1);
if( n == 1)
add( sir, 0, -1);
if( n == 2)
printf("%d\n",cate( sir, 0));
if( n == 3)
printf("%d\n",pref( sir, 0, 0));
}
return 0;
}