前缀统计 Page79 字典树
初学字典树
如果仅将结尾标记,是不严谨的,多个相同字符串的情况就会被默认视为1个字符串
代码:
#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define ull unsigned long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x<b;x++)
#define W(x) printf("%d\n",x)
#define WW(x) printf("%lld\n",x)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=1e6+7;
const int INF=1e9;
const ll INFF=1e18;
char str[maxn];
int trie[maxn][26],tot=1,num[maxn],n,m;
void insert_(char* str)
{
int len=strlen(str),p=1;
repp(k,0,len)
{
int ch=str[k]-'a';
if (trie[p][ch]==0)trie[p][ch]=++tot;
p=trie[p][ch];
}
num[p]++;
}
int search_(char* str)
{
int len=strlen(str),p=1,ans=0;
repp(k,0,len)
{
int ch=str[k]-'a';
ans+=num[trie[p][str[k]-'a']];
p=trie[p][str[k]-'a'];
if (p==0)break;
}
return ans;
}
int main()
{
scanf("%d%d",&n,&m);
rep(i,1,n)scanf("%s",str),insert_(str);
rep(i,1,m)scanf("%s",str),W(search_(str));
return 0;
}