hdu1251 统计难题 数据结构之Trie树

哈哈,第一次用Trie树,从网上找了个模板改了改,然后自己写了search()。

题目很简单,就不解释了。

#include<stdio.h>
#include <string.h>

const int sonnum=26, base='a';
struct Trie{
	int num;  //记录有多少个单词能到达次,也即相同前缀的个位
	//bool terminal; //判断是否是结束节点
	struct Trie *son[sonnum];
	Trie()
	{
		num=1;
		// terminal=false;
		memset(son,NULL,sizeof(son));
	}
};

void Insert(Trie *root, char *s)
{
	Trie *temp=root;
	while(*s)
	{
		if(temp->son[*s-base]==NULL)   //不存在 则建立
			temp->son[*s-base]=new Trie();//NewTrie();
		else 
		{
			temp->son[*s-base]->num++;
		}
		temp=temp->son[*s-base];
		s++;
	}
	//temp->terminal=true;  //到达尾部,标记一个串
}

int search(Trie *root,char a[])
{
	Trie *temp=root;
	int i=0;
	while(a[i])
	{
		if(temp->son[a[i]-base]!=NULL)
			temp=temp->son[a[i]-base];
		else return 0;
		i++;
	}
	return temp->num;
}

int main()
{
	char a[11];
	Trie *root=new Trie();
	while(gets(a))
	{
		if(a[0]=='\0')break;
		Insert(root,a);
	}
	while(gets(a))
		printf("%d\n",search(root,a));
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值