简单前缀树


hdu1251统计难题为例

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
	int n;
	node *next[26];
}*trid;

struct node * tree ;

void build(char *ch)
{
	int len=strlen(ch);
	int i,j;
	if(len==0)        //插入为0...直接返回
		return ; 
	trid current, temp;    //current表示当前节点,temp表示新的被tree指向的节点
	current=tree;
	for(i=0;i<len;i++)
	{
		if(current->next[ch[i]-'a']!=0)   //重要!!  判断该节点是否为空指针(则前缀没在树中)
		{			
			current=current->next[ch[i]-'a'];   //将current指向它的next,形成链表
			    //   (如果是用tree指的话,后面将都连在tree上,形成不了链表)
			current->n=	current->n+1;
		}
		else
		{
			temp=(trid)malloc(sizeof(node));
			for(j=0;j<26;j++)    //  每次新建节点后都要预处理!!!!
				temp->next[j]=0;
			current->next[ch[i]-'a']=temp;    //current指向temp
			current=temp;    //(链表构造规则:先指向,后转移)
			temp->n=1;
		}
	}
	return ;
}

int find(char *s)
{
	int i;
	int len=strlen(s);
	if(len==0)
		return 0;
	trid current=tree;
	for(i=0;i<len;i++)
	{
		if(current->next[s[i]-'a']!=0)   
			current=current->next[s[i]-'a'];			
		else
			return 0;
	}
	return current->n;    //输出前缀为s的单词长度
}

int main()
{
	char ch[20],s[10];
	int i;
	tree=(trid)malloc(sizeof(node));
	for(i=0;i<26;i++)    //   对next , n 进行预处理  next表示下一位的指针,n表示出现的次数
		tree->next[i]=0;
	while(gets(ch),strcmp(ch,"")!=0)    //遇到空一行结束字母表的输入
		build(ch);
	while(scanf("%s",s)!=EOF)
	{
		i=find(s);
		printf("%d\n",i);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值