Cod sursa(job #1135320)

Utilizator federerUAIC-Padurariu-Cristian federer Data 7 martie 2014 18:03:20
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<fstream>
#include<cstring>
using namespace std;

ifstream fin("trie.in");
ofstream fout("trie.out");

int op, N;
char c[40];

struct Trie{
	int freq, words;
	Trie *sons[27];
	Trie()
	{
		int i;
		for (i = 0; i <= 26; ++i)
			sons[i] = NULL;
		freq = words = 0;
	}
};
Trie *T;

void Insert(Trie *nod)
{
	int i, next;
	for (i = 0; i < N; ++i)
	{
		next = c[i] - 'a';
		if (nod->sons[next] == NULL)
			nod->sons[next] = new Trie;
		nod = nod->sons[next];
		nod->freq++;
	}
	nod->words++;
}
void Delete(Trie *nod)
{
	int i, next;
	for (i = 0; i < N; ++i)
	{
		next = c[i] - 'a';
		nod = nod->sons[next];
		nod->freq--;
	}
	nod->words--;
}
int Search(Trie *nod)
{
	int i, next;
	for (i = 0; i < N; ++i)
	{
		next = c[i] - 'a';
		if (nod->sons[next] == NULL)
			return 0;
		nod = nod->sons[next];
	}
	return nod->words;
}
int Prefix(Trie *nod)
{
	int i, next, sol = 0;
	for (i = 0; i<N; i++)
	{
		next = c[i] - 'a';
		if (nod->sons[next] == NULL)
			break;
		nod = nod->sons[next];
		if (nod->freq>0) sol++;
		else break;
	}
	return sol;
}
int main()
{
	T = new Trie;
	while (fin >> op >> c)
	{
		N = strlen(c);
		switch (op)
		{
		case 0: Insert(T); break;
		case 1: Delete(T); break;
		case 2: fout << Search(T) << '\n'; break;
		case 3: fout << Prefix(T) << '\n'; break;
		}
	}
	return 0;
}