nyoj685查找字符串(字典树)

13 篇文章 0 订阅
#include<stdio.h>//685查找字符串
struct Trie{
	int count;
	Trie *next[30];
};
Trie *root;;
int turn(char c)//把字符转换成数组序号
{
	if(c>='a' && c<='z')
		return c-'a';
	else if(c=='@')
		return 26;//@
	else 
		return 27;//  +
}
void insert(char *s)//插入一个字符串
{
	if(root==NULL || *s=='\0')
		return ;
	int i;
	Trie *p=root;
	while(*s!='\0')
	{
		if(p->next[turn(*s)]==NULL)//字符串不存在,则创建
		{
			Trie *temp=new Trie;
			for(i=0;i<30;i++)
				temp->next[i]=NULL;
			temp->count=0;//付初值0
			p->next[turn(*s)]=temp;
		}
		p=p->next[turn(*s)];
		s++;
	}
	p->count++;
}
int Tfind(char *s)
{
	Trie *p=root;
	while(p!=NULL && *s!='\0')
	{
		p=p->next[turn(*s)];
		s++;
	}
	return p==NULL?0:p->count;//注意如果字符串不存在也是0;不存在时候p==NULL
}
void del(Trie *p)//删除,oj提交的时候建议不删除,因为这个也耗时间。系统自动会回收,但是自己写的时候要注意。
{
	int i;
	for(i=0;i<30;i++)
	{
		if(p->next[i]!=NULL)
			del(p->next[i]);
	}
	delete p;
}
int main()
{
	int T;
	int n,m;
	int i;
	char s[20];
	scanf("%d",&T);
	getchar();
	while(T--)
	{
		root=new Trie;
		for(i=0;i<30;i++)
			root->next[i]=NULL;
		root->count=0;
		scanf("%d%d",&n,&m);
		for(i=0;i<n;i++)
		{
			scanf("%s",s);
			insert(s);
		}
		while(m--)
		{
			scanf("%s",s);
			printf("%d\n",Tfind(s));
		}
		del(root);
	}
	return 0;
}

我也是即学即用。今天刚看的字典树,今天用上的第一个程序、自己理解不难,我就不加上注释了。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值