统计难题
题意:
给出一张单词表,每行一个单词,单词的长度不超过10 (只有小写字母组成,不会有重复的单词出现),要求统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
注意:本题只有一组测试数据,处理到文件结束.
数据范围:
单词的长度不超过10
解题思路:
map函数
字典树
刚开始做这题的时候其实是被它的输入问题給卡住了,因为这题是通过一个空行
来划分单词表和问题的,但我总是不能准确地作出判断来划分,后来看了 discuss 得知了一些判断方法。
这道题是我用 map 函数和字典树做的第一道题,可以说是我了解并初步学会使用 map 函数和字典树的入门题吧,值得纪念O(∩_∩)O~
代码:
① map函数:
Exe.Time : 764MS | Exe.Memory : 22532K
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;
map<string,int> mp;
int main()
{
string word="";
char c,ant[11];
while(1){
c=getchar();
if(c=='\n'){
c=getchar();
word="";
}
if(c=='\n')
break;
word+=c;
mp[word]++;
}
while(cin>>ant){
cout<<mp[ant]<<endl;
}
return 0;
}
② 字典树:
Exe.Time : 124MS | Exe.Memory : 40916K
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
using namespace std;
#define INF 0x3f3f3f
#define zero 1e-7
typedef long long ll;
const int N=1e5+7;
int tree[26*N][26]={0};//Exe.Time 124MS Exe.Memory 40916K
int cnt[26*N]={0};//记节点出现次数来代表字符串前缀出现次数
int k=0;//节点标号
void inSert(char *s) {
int p=0, len=strlen(s);
for(int i=0; i<len; i++) {
int c=s[i]-'a';
if(!tree[p][c])
tree[p][c]=++k;
//printf("cnt[%d][%d]=%d\t", p, c, cnt[p][c]);
p=tree[p][c];
cnt[p]++;
}
return ;
}
int Search(char *s) {
int p=0, len=strlen(s);
for(int i=0; i<len; i++) {
int c=s[i]-'a';
if(!tree[p][c]) return 0;
p=tree[p][c];
}
return cnt[p];
}
int main() {
char s[50];
// memset(cnt, 0, sizeof(cnt));
// memset(tree, 0, sizeof(tree));
//事实证明,cnt、tree数组的清零不能用memset,否则会Memory Limit
//Exe.Time 109MS Exe.Memory 75424KExceeded
while(gets(s)) {
if(!s[0])
//或if(!strlen(s))
//或if(!strcmp(s, "\0"))
break;
inSert(s);
}
while(gets(s))
printf("%d\n", Search(s));
return 0;
}