1. 程式人生 > >HDU 1251 - 統計難題 (字典樹)

HDU 1251 - 統計難題 (字典樹)

Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為字首的單詞數量(單詞本身也是自己的字首).

Input

輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串.

注意:本題只有一組測試資料,處理到檔案結束.

Output

對於每個提問,給出以該字串為字首的單詞的數量.

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0

思路:

     字典樹模板題。

     一開始用G++交的結果記憶體超限,但是改為C++就AC了。

程式碼:

#include<stdio.h>
#include<string.h>
struct node
{
	int count;
	node* next[26];
	node()
	{
		count=0;
		memset(next,0,sizeof(next));
	}
};
node* root = NULL;
void build(char* s)
{
	node* p=root;
	int len,i;
	len=strlen(s);
	for(i=0;i<len;i++)
	{
		if(p->next[s[i]-'a']==0)
		{
			p->next[s[i]-'a']=new node;
		}
		p=p->next[s[i]-'a'];
		p->count++;
	}
}
void find(char* s)
{
	int i,len;
	node* p=root;
	len=strlen(s);
	for(i=0;i<len;i++)
	{
		if(p->next[s[i]-'a']==0)
		{
			printf("0\n");
			return;
		}
		else
			p=p->next[s[i]-'a'];
	}
	printf("%d\n",p->count);
}
int main()
{
	root=new node;
	char str[50];
	while(gets(str))
	{
		if(strcmp(str,"")==0)
			break;
		build(str);
	}
	
	while(gets(str))
	{
		find(str);
	}
	return 0;
}