Problem-solving ideas
Knowledge point: dictionary tree
(Hmm, I just came to the Amway blog ^ _^)
After learning the basic operations of the dictionary tree, come back and look at this question, ah, template question. . .
First put NNStore N strings in the dictionary tree, letv [p] v [p]v [ p ] represents the number of character strings ending with node p on the dictionary tree.
Calculate the answer: we traverse the string T, the answer is∑ x ϵ p [T] v [p] \sum _{x\epsilon p[T]} v[p]∑xϵp[T]v[p]
( p [ T ] p[T] p [ T ] represents the set of node numbers that T has traversed on the dictionary tree)
Code
#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
char a[1000010],s[1000010];
int n,m,trie[1000010][30],v[1000010],lyx=1;
void insert(){
//往字典树加入一个字符串
int len=strlen(a+1),p=1,c=0;
for(int i=1;i<=len;i++)
{
c=a[i]-'a'+1;
if(!trie[p][c])
trie[p][c]=++lyx;
p=trie[p][c];
}
v[p]++;
// cout<<v[p]<<" "<<p;
}
int get(){
//查询
int len=strlen(s+1),p=1,ans=0,c=0;
for(int i=1;i<=len;i++)
{
c=s[i]-'a'+1;
if(!trie[p][c])
return ans;
p=trie[p][c];
ans+=v[p];
}
return ans;
}
int main() {
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%s",a+1);
insert();
}
for(int i=1;i<=m;i++)
{
scanf("%s",s+1);
printf("%d\n",get());
}
}