hdu 1251 (字典树)

点击打开链接


第一次写字典树。。


#include"stdio.h"
#include"string.h"
#include"stdlib.h"
struct tree
{
	struct tree *child[26];
	int n;
};
struct tree *root;
void insert(char *p)
{
	int i,j;
	int len;
	struct tree *cur,*nee;
	cur=root;
	len=strlen(p);
	for(i=0;i<len;i++)
	{
		if(cur->child[p[i]-'a']!=0)
		{
			cur=cur->child[p[i]-'a'];
			cur->n++;
		}
		else
		{
			nee=(struct tree*)malloc(sizeof(struct tree));
			for(j=0;j<26;j++)
				nee->child[j]=0;
			nee->n=1;
			cur->child[p[i]-'a']=nee;
			cur=nee;
			cur->n=1;
		}
	}
}
int find(char *p)
{
	int i;
	int len;
	struct tree *cur;
	cur=root;
	len=strlen(p);
	if(len==0)return 0;
	for(i=0;i<len;i++)
	{
		if(cur->child[p[i]-'a']!=0)
			cur=cur->child[p[i]-'a'];
		else return 0;
	}
	return cur->n;
}
int main()
{
	int i;
	char ss[11];
	root=(struct tree*)malloc(sizeof(struct tree));
	for(i=0;i<26;i++)
		root->child[i]=0;
	root->n=0;
	while(gets(ss),strcmp(ss,"")!=0)
		insert(ss);
	while(gets(ss)!=0)
		printf("%d\n",find(ss));
	return 0;
}



你可能感兴趣的:(hdu 1251 (字典树))