统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 61310 Accepted Submission(s): 21233
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
ba
b
band
abc
Sample Output
2
3
1
0
这是一道字典树经典题,,,也就是为了 存一下模板 hhhhhh
……一直以来以为字典树很难,,,总是回避这个问题,,今天看了一下,,发现也不是那么难,,
今天学习的博客推荐一下:https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
map 解法
#include <bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
map<string,int> mapp;
char s[101];
while(gets(s))
{
if(strlen(s)==0) break;
for(int i=strlen(s);i>0;i--)
{
s[i]='\0';
mapp[s]++;
}
}
while(gets(s))
{
cout<<mapp[s]<<endl;
}
return 0;
}
字典树代码:
数组版:(首选)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#define ll long long
#define Max 1000010
#define inf 0x3f3f3f3f
using namespace std;
int trie[Max][26]; //数组形式定义字典树,值存储的是下一个字符的位置
int num[Max]={0}; //附加值,以某一字符串为前缀的单词的数量
int pos=1;
void Insert(char word[]) { //在字典树中插入某个单词
int i;
int c=0;
for(i=0;word[i];i++) {
int n=word[i]-'a';
if(trie[c][n]==0) //如果对应字符还没有值
trie[c][n]=pos++;
c=trie[c][n];
num[c]++;
}
}
int Find(char word[]) { //返回以某个字符串为前缀的单词的数量
int i;
int c=0;
for(i=0;word[i];i++) {
int n=word[i]-'a';
if(trie[c][n]==0)
return 0;
c=trie[c][n];
}
return num[c];
}
int main() {
char word[11];
while(gets(word)) {
if(word[0]==NULL) //空行。gets读入的回车符会自动转换为NULL。
break;
Insert(word);
}
while(gets(word))
printf("%d\n",Find(word));
return 0;
}
链表版:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#define ll long long
#define Max 1000010
#define inf 0x3f3f3f3f
using namespace std;
struct Trie{ //字典树定义
Trie* next[26];
int num; //以当前字符串为前缀的单词的数量
Trie() //构造函数
{
int i;
for(i=0;i<26;i++){
next[i] = NULL;
}
num=0;
}
};
Trie root;
void Insert(char word[]) //将字符串word插入到字典树中
{
Trie *p=&root;
int i;
for(i=0;word[i];i++){ //遍历word的每一个字符
if(p->next[word[i]-'a']==NULL) //如果该字符没有对应的节点
p->next[word[i]-'a'] = new Trie; //创建一个
p = p->next[word[i]-'a'];
p->num++;
}
}
int Find(char word[]) //返回以字符串word为前缀的单词的数量
{
Trie *p=&root;
int i;
for(i=0;word[i];i++){ //在字典树找到该单词的结尾位置
if(p->next[word[i]-'a']==NULL)
return 0;
p = p->next[word[i]-'a'];
}
return p->num;
}
int main()
{
char word[11];
while(cin.getline(word,12)){ //输入单词
if(strlen(word)==0||word[0]==' ') //如果读入字符串的长度为0或者是空格,说明读入的是空行
break;
Insert(word);
}
while(scanf("%s",word)!=EOF){
printf("%d\n",Find(word)); //返回word为前缀的单词的数量
}
return 0;
}