hdu 1251 統計難題

Problem Description

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

Input

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

注意:本題只有一組測試數據,處理到文件結束.

Output

對於每個提問,給出以該字符串爲前綴的單詞的數量.

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1

0

這個題是一道字典樹的題目, 算是入門練手的把 ,下面將用兩種方法來寫

一個是指針建樹 的寫法,,另一個是用數組來模擬

法一:

用字典樹模版

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
const int kind=26;
struct node
{
	int  count;
	node *zhi[kind];
	node ()
	{
		count=0;
		for(int i=0;i<kind;i++)
		{
			zhi[i]=NULL;
		}
	}
};

node *p,*root=new node();

void createtree(char *s)
{
	int i,k;
	for(i=0,p=root;s[i];i++)
	{
		k=s[i]-'a';
		if(p->zhi[k]==NULL)
		{
			p->zhi[k]=new node();
		}
		p=p->zhi[k];
		p->count++;
	}
}

/*void clear(node *p)
{
	if(p==NULL)  return;
	for(int i=0;i<26;i++)
	if(p->zhi[i]!=NULL)
	{
		clear(p->zhi[i]);
	}
	delete p;
	root=NULL;
	return ;
}*/

int find(char *s)
{
	int i,k;
	for(p=root,i=0;s[i];i++)
	{
		k=s[i]-'a';
		if(p->zhi[k]==NULL)
		break;
		p=p->zhi[k];
	}
	if(s[i]) return 0;
	return p->count;
}
 

int main()
{
	char s[11];
	while(gets(s)&&s[0]!='\0')
	{
		createtree(s);
	}
	while(gets(s))
	{
		printf("%d\n",find(s));
	}
	//clear(root);
	return 0;
}


法二: 數組模擬


#include<stdio.h>
#include<string.h>
#define maxn 400000
int shu[maxn][26];
int pass[maxn];
int main()
{
	int i;
	char s[20];
	int q=1,cur;
	memset(shu,-1,sizeof(shu));
	while(gets(s),strlen(s)>0)
	{
		int l=strlen(s);
		cur=0;
		for(i=0;i<l;i++)
		{
			if(shu[cur][s[i]-'a']==-1)
			{
				shu[cur][s[i]-'a']=q;
				pass[q]=0;
				q++;
			}
			cur=shu[cur][s[i]-'a'];
			pass[cur]++;
		}
	}
	while(gets(s))
	{
		int num=0,cur=0;
		int l=strlen(s);
		for(i=0;i<l;i++)
		{
			if(shu[cur][s[i]-'a']==-1)
			break;
			
			cur=shu[cur][s[i]-'a'];
			if(i==l-1) num=pass[cur];	
		}
		printf("%d\n",num);
	}
	return 0;
} 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章