Cod sursa(job #1962761)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 12 aprilie 2017 01:02:15
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>
#define MaxN 1005

using namespace std;

FILE *IN,*OUT;

int Type;
char WORD[25];
struct Trie
{
	int Cnt,EOW;
	Trie *Son[26];
	Trie()
	{
		Cnt=EOW=0;
		for(int i=0;i<26;i++)
			Son[i]=NULL;
	}
}*Root=NULL;
Trie* Add(Trie *node,char *w)
{
	if(node==NULL)
		node=new Trie;
	node->Cnt++;
	if(*w!=0)
		node->Son[*w-'a']=Add(node->Son[*w-'a'],w+1);
	else node->EOW++;
	return node;
}
Trie* Delete(Trie *node,char *w)
{
	node->Cnt--;
	if(*w==0)
		node->EOW--;
	else node->Son[*w-'a']=Delete(node->Son[*w-'a'],w+1);
	if(node->Cnt==0)
	{
		delete node;
		node=NULL;
	}
	return node;
}
int Query_Count(Trie *node,char *w)
{
	while(1)
	{
		if(*w==0)
			return node->EOW;
		else node=node->Son[*w-'a'],w++;
	}
}
int Query_Length(Trie *node,char *w)
{
	int L=0;
	while(*w&&node->Son[*w-'a']!=NULL)
	{
		L++;
		node=node->Son[*w-'a'];
		w++;
	}
	return L;
}
int main()
{
	IN=fopen("trie.in","r");
	OUT=fopen("trie.out","w");
	
	Root=new Trie;
	while(fscanf(IN,"%d %s",&Type,WORD)!=-1)
	{
		if(Type==0)
			Root=Add(Root,WORD);
		else if(Type==1)
			Root=Delete(Root,WORD);
		else if(Type==2)
			fprintf(OUT,"%d\n",Query_Count(Root,WORD));
		else fprintf(OUT,"%d\n",Query_Length(Root,WORD));
		memset(WORD,0,sizeof WORD);
	}

	return 0;
}