Cod sursa(job #300883)

Utilizator snaked31Stanica Andrei snaked31 Data 7 aprilie 2009 19:14:13
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <stdio.h>
#include <string.h>

#define nm 25
#define sigma 27

struct trie

{
	int nr, nrs;
	trie *son[sigma];

	trie ()

	{
		nr = 0;
		nrs = 0;
		memset(son, 0, sizeof(son));
	}
};

trie *T;

int t, slen;
char s[nm];


void t_add(char *s)

{
	trie *nod = T;

	int i;

	for (i=0; i<=slen; ++i)
	{
		if (i == slen)
		{
			nod  -> nr ++;
		}
		else
		{
			if (nod -> son[s[i]-'a'] == 0)
			{
				nod -> son[s[i]-'a'] = new trie;
				nod -> nrs ++;
			}
			nod = nod -> son[s[i]-'a'];
		}
	}
}


int t_remove(trie *nod, char *s, int slen)

{
	/*trie *nod = T;

	int i;

	for (i=0; i<slen; ++i)
	{
		
		if (i == (slen -1))
		{
			nod -> nr --;
			if (nod -> nrs == 0)
				delete nod;
		}
		nod = nod -> son[s[i] - 'a'];
	}*/

	if (slen == 0)
	{
		nod -> nr --;
	}
	else
	if (t_remove(nod -> son[*s - 'a'], s+1, slen-1))
	{
		nod -> son[*s-'a'] = 0;
		nod -> nrs --;
	}

	if ( nod -> nrs == 0 && nod -> nr == 0 && nod != T)
	{
		delete nod;
		return 1;
	}

	return 0;
}


void t_print(char *s)

{
	trie *nod = T;

	int i;

	for (i=0; i<=slen; ++i)
	{
		if (i == slen)
		{
			printf("%d\n", nod -> nr);
		}
		else
		if (nod != 0)
			nod = nod -> son[s[i] - 'a'];
		else
		{
			printf("%d\n", 0);
			i = slen+1;
		}
	}


}


void t_printpref( char *s)

{
	trie *nod = T;

	int i, k = 0;

	for (i=0; i<slen; ++i)
	{
		if (nod -> son[s[i] - 'a'] == 0)
		{
			i = slen;
		}
		else
		{
			++k;
			nod = nod -> son[s[i] - 'a'];
		}
	}
	printf("%d\n", k);

}



int main()

{
	freopen("trie.in", "r", stdin);
	freopen("trie.out","w",stdout);

	T = new trie;
	T -> nr = 0;

	while (!feof(stdin))
	{
		scanf("%d ", &t);
		scanf("%s ", s);
		slen = strlen(s);

		if (t == 0)
			t_add(s);
		else
		if (t == 1)
		{
			t_remove(T, s, slen);
		}
		else
		if (t == 2)
		{
			t_print(s);
		}
		else
			t_printpref(s);
	}

	return 0;
}