现在的位置: 首页 > 综合 > 正文

杭电1251 字典树典型应用

2013年07月28日 ⁄ 综合 ⁄ 共 1342字 ⁄ 字号 评论关闭

           一道字典树的简单题,,不过对于我这种刚学字典树的菜鸟来说,还是纠结了很长时间,,,可以留下来做个模板,,,,题目:

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 


Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.

 


Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 


Sample Input
banana band bee absolute acm ba b band abc
 


Sample Output
2 3 1 0

ac代码:

#include <iostream>
#include <cstdio>
#include <string.h>
#include <malloc.h>
using namespace std;
struct Tire
{
  int count;
  struct Tire *tire[26];       
}*a;
void init(){
  a=(Tire*)malloc(sizeof(Tire));
  for(int i=0;i<26;++i)
  a->tire[i]=NULL;     
}
void insert(char ch[])
{
	//printf("%s\n",ch);
  int length=strlen(ch);
  //printf("%d\n",length);
  Tire *head=a;
  int i,j,k;
  for(i=0;i<length;++i)
  {
    k=(int)(ch[i]-97);
	//printf("%d\n",k);
	if(head->tire[k]!=NULL)
	{
	  head=head->tire[k];
	  head->count++;
	}
	 else{
      head->tire[k]=new Tire;
      head=head->tire[k];
      head->count=1;
      for(j=0;j<26;++j)
      head->tire[j]=NULL;                        
    }                   
    
  }     
  
}
int find(char chh[]){
  int llen=strlen(chh);
  //printf("%d\n",llen);
  Tire *newhead=a;
  int i,j,k;
  for(i=0;i<llen;++i){
    k=(int)(chh[i]-97);
	if(newhead->tire[k]!=NULL)
		newhead=newhead->tire[k];
	else
	{return 0;}
  }
  return newhead->count;
}
int main()
{
  char s[10],ss[10];
  init();
  int len,num=0;
  while(gets(s))
  {
    len=strlen(s);
	//printf("%d\n",len);
    if(len==0)  break;
	//printf("uuuuu\n");
    insert(s);
	//printf(".....\n");
  }
  while(gets(ss))
  {
	num=0;
    num=find(ss);
    printf("%d\n",num);    
  }
}

抱歉!评论已关闭.