前缀统计【字典树 Trie】
原创
©著作权归作者所有:来自51CTO博客作者Alan_Lowe的原创作品,请联系作者获取转载授权,否则将追究法律责任
前缀统计【字典树 Trie】
CH1601
、ACwing142
#include<bits/stdc++.h>
using namespace std;
#define
const int N = 1e6;
int n,m,num;
string s;
struct Node{
int p;
int son[26];
int flag;
} tree[N + 5];
void build(){
int now = 0;
for(int i = 0;s[i];++i){
if(tree[now].son[s[i] - 'a'] == 0)
tree[now].son[s[i] - 'a'] = ++num;
now = tree[now].son[s[i] - 'a'];
}
tree[now].flag += 1;
}
int find(){
int ans = 0,now = 0;
for(int i = 0;s[i];++i){
if(tree[now].son[s[i] - 'a'])
now = tree[now].son[s[i] - 'a'];
else
break;
ans += tree[now].flag;
}
return ans;
}
signed main(){
cin>>n>>m;
for(int i = 1;i <= n;++i){
cin>>s;
build();
}
for(int i = 1;i <= m;++i){
cin>>s;
cout<<find()<<"\n";
}
return 0;
}