链接
题目描述
给定 N个字符串S1,S2 ,接下来进行M次询问,每次询问给定一个字符串T ,求S1~Sn 中有多少个字符串是 T 的前缀。
样例输入
3 2
ab
bc
abc
abc
efg
样例输出
2
0
思路
用 s 1 . . . s n s_1...s_n s1...sn构建 t r i e trie trie树,然后用一个 c c c记录以当前字母为结尾的字符串的个数,然后再用字符串 t t t跑trie树即可
代码
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
char s[1000005], t[1000005];
int tot = 1, n, m, ans;
int cnt[1000005], trie[1000005][26];
void ins() {
scanf("%s", s + 1);
int len = strlen(s + 1), p = 1;
for (int i = 1; i <= len; ++i) {
int ch = s[i] - 'a';
if (!trie[p][ch])
trie[p][ch] = ++tot;
p = trie[p][ch];
}//构建trie树
cnt[p]++;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) ins();
for (int i = 1; i <= m; ++i) {
ans = 0;
scanf("%s", t + 1);
int len = strlen(t + 1), p = 1;
for (int j = 1; j <= len; ++j) {
int ch = t[j] - 'a';
if (trie[p][ch])
p = trie[p][ch], ans += cnt[p];//统计答案
else
break;
}
printf("%d\n", ans);
}
return 0;
}