hdu1251(简单的字典树模版)

#include<iostream>
#include<string.h>
using namespace std;
#define max 26
typedef struct tree
{
	tree *next[26];
	int v;
}tree;
tree tmp;
tree *root=&tmp;
void creat(char str[])
{
	int len=strlen(str);
//	printf("\n%d\n",len);
	tree *p=root,*q;
	for(int i=0;i<len;i++)
	{
		int x=str[i]-'a';
		//printf("\n%d\n",x);
		if(p->next[x]==NULL)
		{
			q=(tree *)malloc(sizeof(tree));
			q->v=1;
			for(int j=0;j<max;j++)
				q->next[j]=NULL;
			p->next[x]=q;
			p=p->next[x];
		}
		else
		{
			p->next[x]->v++;
			p=p->next[x];
		}
	}
}
int find(char str[])
{
	int len=strlen(str);
	tree *p=root;
	for(int i=0;i<len;i++)
	{
		int x=str[i]-'a';
		p=p->next[x];
		if(p==NULL)
			return 0;
	}
	return p->v;
}
int main()
{
	char s[15];
	for(int i=0;i<max;i++)
		root->next[i]=NULL;
	while(gets(s)&&s[0]!='\0')
		creat(s);
	memset(s,0,sizeof(s));
	while(scanf("%s",s)>0)
	{
		printf("%d\n",find(s));
	}
	return 0;
}

 

posted @ 2012-12-07 11:50  紫忆  阅读(178)  评论(0编辑  收藏  举报