经典字典树题
就是输入不太友好,因为我平时不喜欢用 gets()
我一般用 scanf(“%[^\n]”,ch) 来代替 gets(ch) ,ch 是 char* 类型的,这里利用了正则表达式的性质,让 scanf() 达到了gets()的效果,也保留了 scanf() 的优点
如果有大佬可以不用gets()函数的,请留言告知,万分感谢!
我的代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=400000+100;
int trie[maxn][26],sum[maxn],tot;
void insert(char* ch){
int len=strlen(ch);
int root=0;
for(int i=0;i<len;i++){
int ind=ch[i]-'a';
if(!trie[root][ind]) trie[root][ind]=++tot;
sum[trie[root][ind]]++;
root=trie[root][ind];
}
}
int search(char* ch){
int len=strlen(ch);
int root=0;
for(int i=0;i<len;i++){
int ind=ch[i]-'a';
if(!trie[root][ind]) return 0;
root=trie[root][ind];
}
return sum[root];
}
int main(){
char ch[20];
while(gets(ch)){
if(ch[0]=='\0') break;
insert(ch);
}
while(scanf("%s",ch)==1){
printf("%d\n",search(ch));
}
}