Cod sursa(job #237707)

Utilizator ProtomanAndrei Purice Protoman Data 30 decembrie 2008 14:50:39
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

struct trie
{
	int nrc, cnt;
	trie *fii[26];
	trie()
	{
		memset(fii, 0, sizeof(fii));
		cnt = nrc = 0;
	}
} *rad_ti = new trie;
int oper;
char str[32];

void insert_ti(trie *nod, char s[])
{
	if (s[0] == '\n')
	{
		nod->cnt++;
		return;
	}
	if (nod->fii[s[0] - 'a'] == 0)
	{
		nod->nrc++;
		nod->fii[s[0] - 'a'] = new trie;
	}
	insert_ti(nod->fii[s[0] - 'a'], s + 1);
}

bool delete_ti(trie *nod, char s[])
{
	if (s[0] == '\n')
		nod->cnt--;
	else if (delete_ti(nod->fii[s[0] - 'a'], s + 1))
	{
		nod->nrc--;
		nod->fii[s[0] - 'a'] = 0;
	}
	if (!nod->cnt && !nod->nrc && nod != rad_ti)
	{
		delete(nod);
		return 1;
	}
	return 0;
}

int cauta_ti(trie *nod, char s[])
{
	if (s[0] == '\n')
		return nod->cnt;
	if (nod->fii[s[0] - 'a'])
		return cauta_ti(nod->fii[s[0] - 'a'], s + 1);
	return 0;
}

int pref_ti(trie *nod, char s[], int lvl)
{
	if (s[0] == '\n')
		return lvl;
	if (nod->fii[s[0] - 'a'])
		return pref_ti(nod->fii[s[0] - 'a'], s + 1, lvl + 1);
	return lvl;
}

int main()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	scanf("%d ", &oper);
	fgets(str, 25, stdin);
	while (!feof(stdin))
	{
		if (!oper)
			insert_ti(rad_ti, str);
		if (oper == 1)
			delete_ti(rad_ti, str);
		if (oper == 2)
			printf("%ld\n", cauta_ti(rad_ti, str));
		if (oper == 3)
			printf("%ld\n", pref_ti(rad_ti, str, 0));
		scanf("%d ", &oper);
		fgets(str, 25, stdin);
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
}