字典树初步
朴素字符串查找
字典树
例题
link:1.前缀判定 - 蓝桥云课
code
// comment by english only for practice
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
const ll MAXN = 2e6 + 10;
ll nex[MAXN][30], cnt[MAXN], idx = 2;// idx inited as 2 bc 1 is the root n idx=1 represent null, enable its sons be the bgns of all string
// nex[idx][ch] : begin with index idx, its ch son`s index
void insert(char s[])
{int x = 1;// 1 is the root of trie treefor(int i = 0; s[i]; i++){if(!nex[x][s[i] - 'a'])nex[x][s[i] - 'a'] = idx++;x = nex[x][s[i] - 'a'];cnt[x]++;// bc this question is asking for 前缀和 not 'totally same strings', so when move 'cnt[x]++' from the outside of the loop into the inside }// if the question need us to count the totally same strings but not same 前缀和, we should move 'cnt[x]++' out of the for-loop
}ll count(char t[])
{int x = 1;for(int i = 0; t[i]; i++){x = nex[x][t[i] - 'a'];}return cnt[x];
}int main()
{ll n, m; cin>>n>>m;while(n--){char s[MAXN]; cin>>s;insert(s);}while(m--){char t[MAXN]; cin>>t;cout<<(count(t) ? "Y" : "N")<<endl;}return 0;
}