题意:给点一序列的字符串,再给你一些单词,问以这个单词为前缀的字符串的个数,注意本身也是自己的前缀
思路:把给定的字符串建立一棵字典树,每一个节点保存的是当前节点为结尾的字符串出现的次数,那么对于给定的单词我们只要去查找字典树即可
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int MAXN = 1000010;
const int N = 26;
struct Node{
int cnt;
Node* child[N];
};
Node node[MAXN];
Node* root;
int pos;
Node* newNode(){
node[pos].cnt = 0;
for(int i = 0 ; i < N ; i++)
node[pos].child[i] = NULL;
return &node[pos++];
}
void insert(char* str){
int len = strlen(str);
Node* s = root;
for(int i = 0 ; i < len ; i++){
int num = str[i]-'a';
if(s->child[num] == NULL)
s->child[num] = newNode();
s = s->child[num];
s->cnt++;
}
}
int search(char* str){
int len = strlen(str);
Node* s = root;
for(int i = 0 ; i < len ; i++){
int num = str[i]-'a';
if(s->child[num] == NULL)
return 0;
s = s->child[num];
}
return s->cnt;
}
int main(){
pos = 0;
root = newNode();
char str[N];
while(gets(str) && str[0] != '\0')
insert(str);
while(scanf("%s" , str) != EOF)
printf("%d\n" , search(str));
return 0;
}