Cod sursa(job #533958)

Utilizator ChallengeMurtaza Alexandru Challenge Data 14 februarie 2011 21:20:29
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <cstring>

using namespace std;

const char InFile[]="trie.in";
const char OutFile[]="trie.out";
const int BUFFERSIZE=64;
const int SIGMA=26;

ifstream fin(InFile);
ofstream fout(OutFile);

struct s_trie
{
	s_trie(){childs=0;count=0;memset(child,0,sizeof(child));}
	int count,childs;
	s_trie *child[SIGMA];
};

char buff[BUFFERSIZE];
s_trie root;

void add_trie(s_trie *node, char *p)
{
	if('a'<=*p && *p<='z')
	{
		int key=*p-'a';
		if(node->child[key]==0)
		{
			++node->childs;
			node->child[key]=new s_trie();
		}
		add_trie(node->child[key],p+1);
	}
	else
	{
		++node->count;
	}
}

int count_trie(s_trie *node, char *p)
{
	if(!('a'<=*p && *p<='z'))
	{
		return node->count;
	}

	int key=*p-'a';
	if(node->child[key]==NULL)
	{
		return 0;
	}

	return count_trie(node->child[key],p+1);
}

int prefix_trie(s_trie *node, char *p)
{
	if(!('a'<=*p && *p<='z'))
	{
		return 0;
	}

	int key=*p-'a';
	if(node->child[key]==NULL)
	{
		return 0;
	}

	return 1+prefix_trie(node->child[key],p+1);
}

bool del_trie(s_trie *node, char *p)
{
	int key=*p-'a';
	if(!('a'<=*p && *p<='z'))
	{
		--node->count;
	}
	else
	{
		if(del_trie(node->child[key],p+1))
		{
			node->child[key]=NULL;
			--node->childs;
		}
	}
	
	if(node->childs==0 && node->count==0 && node!=&root)
	{
		delete node;
		return true;
	}
	return false;
}

int main()
{
	while(fin.getline(buff,sizeof(buff)))
	{
		if(buff[0]=='0')
		{
			add_trie(&root,buff+2);
		}
		else if(buff[0]=='1')
		{
			del_trie(&root,buff+2);
		}
		else if(buff[0]=='2')
		{
			fout<<count_trie(&root,buff+2)<<"\n";
		}
		else if(buff[0]=='3')
		{
			fout<<prefix_trie(&root,buff+2)<<"\n";
		}
		memset(buff,0,sizeof(buff));
	}
	fin.close();
	fout.close();
	return 0;
}