杭电1251

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Trie
{
	struct Trie *Next[26];
	int data;
}node;
node *root;
void Insert(char s[])
{
	int len=strlen(s);
	int i;
	node *p=root;
	node *q;
	for(i=0;i<len;i++)
	{
		if(p->Next[s[i]-'a']==NULL)
		{
			q=(node *)malloc(sizeof(node));
			q->data=1;
			for(int j=0;j<26;j++)
			{
				q->Next[j]=NULL;
			}
			p->Next[s[i]-'a']=q;
			p=p->Next[s[i]-'a'];
		}
		else 
		{
			p->Next[s[i]-'a']->data++;
			p=p->Next[s[i]-'a'];
		}
	}
}
int Query(char s[])
{
	int len=strlen(s);
	int i;
	node *p=root;
	for(i=0;i<len;i++)
	{
		if(p->Next[s[i]-'a']==NULL)
		return 0;
		else 
		p=p->Next[s[i]-'a'];
	}
	return p->data;
}
int main()
{
	char s[15];
	root=(node *)malloc(sizeof(node));
	for(int k=0;k<26;k++)
	{
	root->Next[k]=NULL;
	}
	while(gets(s),s[0])
	{
		Insert(s);
	}
	while(gets(s))
	{
	printf("%d\n",Query(s));
	}
return 0;
}

你可能感兴趣的:(杭电1251)