注意点1:初始化无论用memset还是vector<n,0>的时间复杂度都是o(n),会超时,
要高效利用已知资源,利用上一次的idx初始化。
P8306 【模板】字典树 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
typedef long double ldb;
typedef pair<int, int> pii;
typedef pair<ll, ll> PII;
#define pb emplace_back
//#define int ll
#define all(a) a.begin(),a.end()
#define x first
#define y second
#define ps push_back
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define ve1 vector<ll>
#define ve2 vector<vector<ll>>
void solve();
const int N = 3e6 + 5;
signed main() {
IOS;
ll t;
cin >> t;
while(t--)
solve();
return 0;
}
ll idx,ch[N][10+26*2],cnt[N];
// idx 节点编号,根节点是0
// ch 存储字典树的数组
// cnt 字典树的模版是用来统计单词个数的,这里用来统计前缀个数
void init()//初始化参数
{
for(int i = 0; i <= idx; ++ i)//上一次只用到了最大到idx
{
for(int j = 0; j < 10 + 26 * 2; ++ j)
ch[i][j] = 0;
cnt[i] = 0;//将每个节点的前缀数量归零
}
idx = 0;//别忘了这个,记录节点编号的东西
}
void insert(string s)//建立字典树
{
int p = 0;//根结点是0
for(auto it : s)
{
ll j;
if(it >= '0' && it <= '9') j = it - '0';
else if(it < 'a') j = it - 'A' + 10;
else j = it - 'a' + 26 + 10;//A从26开始
// 上面三行是映射字符,将字符变为数字好处理
if(!ch[p][j]) ch[p][j] = ++ idx;//没有找到
p = ch[p][j];
cnt[p] ++;
}
}
ll query(string s)//查询函数
{
int p = 0;
for(auto it : s)
{
ll j;
if(it >= '0' && it <= '9') j = it - '0';//数字
else if(it < 'a') j = it - 'A' + 10;//A从10开始
else j = it - 'a' + 26 + 10;//小写字母
if(!ch[p][j]) return 0;//字节点的编号不是0,如果是0则没有这条边
p = ch[p][j];
}
return cnt[p];
}
void solve() {
init();//初始化
ll n ,q;
cin >> n >> q;
for(int i = 1; i <= n; ++ i)
{
string s; cin >> s;
insert(s);
}
for(int i = 1; i <= q; ++ i)
{
string s; cin >> s;
cout << query(s) << endl;
}
}