hdu 1251 统计难题(trie树)

本文详细介绍了字典树(Trie Tree)的数据结构及其在编程中的应用,通过具体实例展示了如何使用C语言创建和查找字典树节点,并提供了完整的源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这两天学了下字典树~

参考连接:

http://www.cnblogs.com/cherish_yimi/archive/2009/10/12/1581666.html

http://www.wutianqi.com/?p=1359

以及hdu的lcy老师的课件。

hdoj的1251求前缀字符串的个数,模版水过,参照dd牛模版



#include<stdio.h>//algo:trie tree
#include<string.h>
#include<stdlib.h>
#define MAX 26
typedef struct Trie{
	Trie *next[MAX];
	int flag;
}Trie;
Trie root;
void createTrie(char *str)
{
	int len=strlen(str);
	Trie *p=&root,*q;
	for(int i=0;i<len;i++)
	{
		int id=str[i]-'a';
		if(p->next[id]==NULL)
		{
			q=(Trie *)malloc(sizeof(Trie));
			q->flag=1;//init
			for(int j=0;j<MAX;j++)
				q->next[j]=NULL;
			p->next[id]=q;
			p=p->next[id];
		}
		else 
		{
			p->next[id]->flag++;
			p=p->next[id];
		}
	}
}
int findTrie(char *str)
{
	int len=strlen(str);
	Trie *p=&root;
	for(int i=0;i<len;i++)
	{
		int id=str[i]-'a';//根据需要减去0,或者‘a’或者'A'
		p=p->next[id];
		if(p==NULL)//若为空集,表示不存在以此为前缀的串
			return 0;
	}
	return p->flag;// 此串是字符集中某串的前缀
}
int dealTrie(Trie* T)//释放空间
{
	int i;
	if(T==NULL)	return 0;
	for(i=0;i<MAX;i++)
	{
		if(T->next[i]!=NULL)
			dealTrie(T->next[i]);
	}
	free(T);
	return 0;
}
int main()
{
	char str[15];
	while(gets(str))
	{
		if(str[0]=='\0') break;
		createTrie(str);
	}
	char aim[15];
	while(~scanf("%s",aim))
	{
		int ans=findTrie(aim);
		printf("%d\n",ans);

	}
	//dealTrie(&root);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值