统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 680 Accepted Submission(s): 294
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
为了让这道题AC 真的是太难了 我一开始用G++进行提交 一直是内存超了………后来我看见讨论区里有人讨论说得用C++进行提交 然后我报了试一试的心态提交了 没想到AC了
这道题就是一个字典树的上手题 几乎是模板
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef struct node
{
int v;
struct node *next[26];
}node;
void Insert(node *root,char str[])
{
node *p = root;
node *q;
int len = strlen(str);
for(int i =0;i<len;i++)
{
int id = str[i] -'a';
if(p->next[id]==NULL)
{
q = (node *)malloc(sizeof(node));
q->v = 1;
for(int i =0;i<26;i++)
q->next[i] = NULL;
// memset(q->next,0,sizeof(q->next));
p->next[id] = q;
p = p->next[id];
}
else
{
p = p->next[id];//当在读入一个字符时已经存在了 则只需要以这个为前缀的v加加
p->v++;
}
}
}
int serach(node *root,char str[])
{
node *p = root;
int len = strlen(str);
for(int i=0;i<len;i++)
{
int id = str[i]-'a';
if(p->next[id]==NULL)
return 0;
p = p->next[id];
}
return p->v;
}
void del(node *root)
{
for(int i =0;i<26;i++)
{
if(root->next[i]!=NULL)
free(root->next[i]);
}
free(root);
}
int main()
{
node *root = (node *)malloc(sizeof(node));
root->v = 0 ;
for(int i =0;i<26;i++)
{
root->next[i] = NULL;
}
// memset(root->next,0,sizeof(root->next));
char tt[12];
while(gets(tt))
{
if(strcmp(tt,"")==0) break;
Insert(root,tt);
}
while(~scanf("%s",tt))
{
cout<<serach(root,tt)<<endl;
}
del(root);//别忘记释放内存
return 0;
}