HDU1251【Trie】

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1251

#include
#include
#include

using namespace std;

struct tire
{
	int num;      //这个结点为前缀出现的次数
	tire *nex[26];  //分支
}*root;
void insert(const char *s)  //把s插入root中
{
	tire *p=root;               //保护根节点,每次从根结点(a)开始查询                                                                                                     
	while(*s!='\0')            
	{
		if(p->nex[*s-'a']==NULL)    //如果这个字母为不存在
		{
			p->nex[*s-'a']=new tire;   //new一个分支为[*s-'a']
			p=p->nex[*s-'a'];          //把这个分支赋值给p
			p->num=1;                   //赋值为1,刚new出来,出现一次
			for(int i=0;i<26;i++)
				p->nex[i]=NULL;            //这个分支的分支们为NULL
		}
		else
		{
			p=p->nex[*s-'a'];
			p->num++;
		}
		s++;    //开始下一个字母插入
	}
}
int find(char *s)
{
	tire *p=root;
	while(p!=NULL && *s!='\0')
	{
		if(p->nex[*s-'a']==NULL)
			return 0;               //还未遍历这个前缀结束 就null了,直接返回0
		else
			p=p->nex[*s-'a'];
		s++;
	}
	return p->num;
}
int main()
{
	char s[11];
	root=new tire;
	for(int i=0;i<26;i++)
		root->nex[i]=NULL;
	while(gets(s))
	{
		if(s[0]=='\0')
			break;
		insert(s);
	}
	char str[11];
	while(scanf("%s",str)!=EOF)
	{
		int sum=find(str);
		printf("%d\n",sum);
	}
	return 0;
}

 

你可能感兴趣的:(做题记录)