Cod sursa(job #414876)

Utilizator marius135Dumitran Adrian Marius marius135 Data 10 martie 2010 17:30:56
Problema Trie Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <stdio.h>
#include <string.h>
#define maxn 100000
int trie[maxn][26];
int nr[maxn];
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;
	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[22];
	int n;
	for( int i = 0; i < maxn; ++i)
		for( int j = 0; j < 26; ++j)
			trie[i][j] = -1;
	memset(sir,0,sizeof(sir));
	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;
}