描述
给定N个字符串S1,S2...SN,接下来进行M次询问,每次询问给定一个字符串T,求S1~SN中有多少个字符串是T的前缀。输入字符串的总长度不超过10^6,仅包含小写字母。
输入格式
第一行两个整数N,M。接下来N行每行一个字符串Si。接下来M行每行一个字符串表示询问。
输出格式
对于每个询问,输出一个整数表示答案
样例输入
3 2 ab bc abc abc efg
样例输出
2 0
分析
颓啊……连trie树都写WA了,我还能做什么……仰天长叹,但别沮丧,知道错了,才好改正,加油女孩,你可以的
trie树板题,这倒是没什么好分析的
代码
#include<bits/stdc++.h>
using namespace std;
int n,m,trie[9000009][30],cnt[9000009],tot=1;
char st[1000009];
void insert(){
int len=strlen(st),pos=1;
for(int i=0;i<len;++i){
int c=st[i]-'a';
if(!trie[pos][c]) trie[pos][c]=++tot;
pos=trie[pos][c];
}
cnt[pos]++;//这个地方不是tot,并不是每次都会新建节点好吧
}
int query(){
int res=0,len=strlen(st),pos=1;
for(int i=0;i<len;++i){
int c=st[i]-'a';
if(trie[pos][c]) res+=cnt[trie[pos][c]],pos=trie[pos][c];
else break;
}
return res;
}
int main(){
scanf("%d%d",&n,&m);
int i,j;
for(i=1;i<=n;++i){
scanf("%s",st);
insert();
}
for(i=1;i<=m;++i){
scanf("%s",st);
printf("%d\n",query());
}
return 0;
}
你和你的期望,是前方矗立的路标