【题目来源】
https://www.acwing.com/problem/content/144/
【题目描述】
给定 N 个字符串 S1,S2…SN,接下来进行 M 次询问,每次询问给定一个字符串 T,求 S1∼SN 中有多少个字符串是 T 的前缀。
输入字符串的总长度不超过 10^6,仅包含小写字母。
【输入格式】
第一行输入两个整数 N,M。
接下来 N 行每行输入一个字符串 Si。
接下来 M 行每行一个字符串 T 用以询问。
【输出格式】
对于每个询问,输出一个整数表示答案。
每个答案占一行。
【数据范围】
1≤N,M≤10^5
【输入样例】
3 2
ab
bc
abc
abc
efg
【输出样例】
2
0
【算法分析】
● 关于字典树的介绍,请详见:
https://blog.csdn.net/hnjzsyjyj/article/details/138599488
https://blog.csdn.net/hnjzsyjyj/article/details/138631374
● 在本题代码的 query() 函数中,虽有 p=sn[p][u]; 语句,但发现使用 if(p==0) return ans; 能得出正确结果,但使用 if(sn[p][u]==0) return ans; 无法得出正确结果。从逻辑上看,没有问题。难道是 C++ 有什么未关注到的细节?请广大朋友指正。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
int sn[maxn][26]; //sn[p][u] indicates the serial number
int cnt[maxn]; //number of words ending in the current node
string str;
int idx;
void insert(string s) {
int p=0; //root=0
for(int i=0; i<s.size(); i++) {
int u=s[i]-'a'; //a~z are mapped to 0~25
if(!sn[p][u]) sn[p][u]=++idx;
p=sn[p][u];
}
cnt[p]++;
}
int query(string s) {
int ans=0;
int p=0; //root=0
for(int i=0; i<s.size(); i++) {
int u=s[i]-'a'; //a~z are mapped to 0~25
p=sn[p][u];
if(p==0) return ans;
ans+=cnt[p];
}
return ans;
}
int main() {
int n,m;
cin>>n>>m;
for(int i=1; i<=n; i++) cin>>str, insert(str);
for(int i=1; i<=m; i++) cin>>str, cout<<query(str)<<endl;
return 0;
}
/*
in:
3 2
ab
bc
abc
abc
efg
out:
2
0
*/
【参考文献】
https://oi-wiki.org/string/trie/
https://blog.csdn.net/hnjzsyjyj/article/details/138599488
https://blog.csdn.net/hnjzsyjyj/article/details/138631374
https://www.acwing.com/solution/content/85508/