# 统计难题

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

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

Input

Output

Sample Input
banana band bee absolute acm ba b band abc

Sample Output
2 3 1 0

Author
Ignatius.L

Recommend
Ignatius.L   |   We have carefully selected several similar problems for you:  1247 1671 1298 1800 2846

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 27
typedef struct Node{
int count;//记录当前前缀下单词的个数
struct Node *next[N];//指向下一字符下的状态
bool exit;//当前前缀是否有单词存在 (模板中的记录，本题用不到)
}T,*tire;

T * createNode()
{
//初始化节点
tire node = (tire)malloc(sizeof(T));
node->count=0;
node->exit=false;
memset(node->next,0,sizeof(node->next));

return node;
}

void insert(tire  root,char * word)
{
//根据输入的字符串进行建立操作
tire node = root;
char *p = word;
int id;
while(*p)
{
id = *p - 'a';
if(node->next[id]==NULL)
{
node->next[id] = createNode();
}
node = node->next[id];
++p;
node->count+=1;
}
node->exit = true;
}

int search(tire  root,char *word)
{
//从根节点遍历
tire node = root;
char *p = word;
int id;
while(*p)
{
id = *p-'a';
node=node->next[id];
++p;
if(node==NULL)
{
return 0;
}
}
return node->count;
}

int main()
{
tire root = createNode();
char str[12];
bool flag = false;
while(gets(str))
{
if(flag)
{
printf("%d\n",search(root,str));
}
else
{
if(strlen(str)!=0)
{
insert(root,str);
}
else
flag=true;
}
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：字典树 hdu1251 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)