HDU1251【Trie】

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

#include<iostream>
#include<string>
#include<cstring>

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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值