hdu1251 统计难题 (字典树查找)

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 20855    Accepted Submission(s): 9031


题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=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
 

Author
Ignatius.L




#include <stdio.h>
#include <string>
#include <iostream>
#include <cstdlib>
#include <malloc.h>
#include <cstring>
using namespace std;

typedef struct ac
{
	int v;
	struct ac* child[26];
}tree;
tree *root;
void add(char *s)
{
	int i,j,l=strlen(s);
	tree*a=root,*b;
	for(i=0;i<l;i++)
	{
		int k=s[i]-'a';
		if(a->child[k]!=NULL)
		{
			a=a->child[k];
			a->v++;//如果不为空,标记变量加1,这样就说明到这个节点,有v个字符数有这么长的子串
                           (举例:字符串“abcd”“abc”“ab”,则b这个节点的v=3  所以当后面查找的话如果输入“ab”,则可以返回b位置的v=3,也就是所求结果)
		}
		else
		{
			b=(tree*)malloc(sizeof(tree));//申请内存
			b->v=1;将该位置的标记变量初始化为1;
			for(j=0;j<26;j++)
			{
				b->child[j]=NULL;
			}
			a->child[k]=b;
			a=a->child[k];//a=a->child[k];
			
		}
	}
}
int search(char *s)
{
	int l=strlen(s);
	tree* a=root;
	for(int i=0;i<l;i++)
	{
		int k=s[i]-'a';
		a=a->child[k];
		if(a==NULL)//如果为空,说明字典树中没有该单词
		{
			return 0;
		}
	}
	return a->v;//如上面 所说返回 v;
}
void clear(tree* a)//清空内存
{
	if(a==NULL)
		return ;
	else
	{
		for(int i=0;i<26;i++)
		{
			clear(a->child[i]);
		}
	}
	free(a);
}
int main()
{
	char word[15];
	root=(tree*)malloc(sizeof(tree));//初始化
	root->v=0;                      //初始化
	for(int i=0;i<26;i++)           
	{
		root->child[i]=NULL;  //初始化 (一定不能忘)
	}
	while(gets(word)&&strlen(word))//若果输入空行 停止输入
	{
		add(word);
	}
	//printf("yes");
	while(gets(word))
	{
		printf("%d\n",search(word));
	}
	//printf("2323");
	clear(root);
	return 0;
}


posted @ 2015-04-21 08:48  编程菌  阅读(159)  评论(0编辑  收藏  举报