0
点赞
收藏
分享

微信扫一扫

HDU 1251 统计难题 字典树


统计难题

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


 

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

 

Recommend

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

 

题意:

        给你多个单词,然后在给你一个字符串s,现在要问你以该字符串s为前缀的单词数目有多少个?

分析:

        道题就是一道简单的字典树的入门题,在建树的同时保存单词的前缀的个数即可

#include<cstdio>
#include<iostream>
#include<fstream>
#include<algorithm>
#include<functional>
#include<cstring>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<numeric>
#include<cctype>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<list>
#include<set>
#include<map>
using namespace std;
#define N 300000+5
#define MAX 26

typedef long long ll;

const int maxnode=400000+100;//预计字典树最大节点数目
const int sigma_size=26; //每个节点的最多儿子数

struct Trie
{
int ch[maxnode][sigma_size];//ch[i][j]==k表示第i个节点的第j个儿子是节点k
int val[maxnode];//val[i]==x表示第i个节点的权值为x
int sz;//字典树一共有sz个节点,从0到sz-1标号

//初始化
void clear()
{
sz=1;
memset(ch,0,sizeof(ch));//ch值为0表示没有儿子
memset(val,0,sizeof(val));
}

//在字典树中插入单词s,但是如果已经存在s单词会重复插入且覆盖权值
//所以insert前需要判断一下是否已经存在s单词了
void insert(string s)
{
int u=0,n=s.length();
for(int i=0;i<n;i++)///建立字典树
{
int id=s[i]-'a';
if(ch[u][id]==0)//无该儿子
{
ch[u][id]=sz++;
}
u=ch[u][id];
val[u]++;//标记到目前为止的这个前缀出现的次数
}

}

//在字典树中查找单词s
int find(string s)
{
int n=s.length(),u=0;
for(int i=0;i<n;i++)
{
int id=s[i]-'a';
if(ch[u][id]==0)
return false;
u=ch[u][id];

}
return val[u];
}
};
Trie trie;
int main()
{
char s[100];
trie.clear();
while(gets(s))
{
if(strlen(s)==0) break;
trie.insert(s);
}
while(gets(s))
{
if(strlen(s)==0) break;
printf("%d\n",trie.find(s));
}
return 0;
}

 

举报

相关推荐

0 条评论