hdu1251

字典树入门~
#include<cstdio>
#include<cstdlib>
typedef struct node
{
	int cnt;
	struct node *next[26];
} AC;
AC * create()
{
	AC *p=(AC *)malloc(sizeof(AC));
	p->cnt=1;
	for(int i=0;i<=25;i++)
		p->next[i]=NULL;
	return p;
}
void insert(AC *p,char *s)
{
	int i=0;
	while(s[i])
	{
		int k=s[i]-'a';
		if(p->next[k])
			p->next[k]->cnt++;
		else
			p->next[k]=create();
		p=p->next[k];
		i++;
	}
}
int search(AC *p,char *s)
{
	int i=0,ans=0;
	while(s[i]!=0)
	{
		int k=s[i]-'a';
		if(!p->next[k])return 0;
		ans=p->next[k]->cnt;
		p=p->next[k];
		i++;
	}
	return ans;
}
int main()
{
	AC *p=create();
	char s[15];
	while(gets(s)&&s[0])
	{
		insert(p,s);
	}
	while(scanf("%s",s)!=EOF)
	{
		printf("%d\n",search(p,s));
	}
	return 0;
}

你可能感兴趣的:(struct,search,insert)