题目地址:前缀统计
思路:
先把 n n n 个字符串插入同一棵Trie树中,对于Trie树上的每个节点可以拿一个 c n t cnt cnt数组来维护以当前节点为末尾的字符串的个数。
对于每次询问,在Trie树中检索字符串 T T T 时,累加每次经过的节点的 c n t cnt cnt 值即可得到最终答案。
代码:
#include <bits/stdc++.h>
#define sc scanf
#define pf printf
using namespace std;
typedef long long LL;
const int N = 1e6 + 10;
int trie[N][26], tot = 1, cnt[N];
void insert(string str)
{
int p = 1;
for(int i = 0; i < str.size(); i++) {
int ch = str[i] - 'a';
if(!trie[p][ch]) trie[p][ch] = ++tot;
p = trie[p][ch];
}
cnt[p] ++;
}
int search(string str)
{
int p = 1, sum = 0;
for(int i = 0; i < str.size(); i++) {
p = trie[p][str[i] - 'a'];
sum += cnt[p];
if(p == 0) return sum;
}
return sum;
}
int main()
{
int n, q;
cin >> n >> q;
for(int i = 0; i < n; i++) {
string str;
cin >> str;
insert(str);
}
while(q--) {
string str;
cin >> str;
cout << search(str) << endl;
}
return 0;
}