字典树能够用来查询某单词的前缀在所有单词中出现的次数,有查询和插入两个操作,查询和插入的时间复杂度都是O(n),是一种以空间换时间的方法
LA3942字典树的应用;
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<cctype>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<string>
#define ll long long
#define MAX 300010
#define INF INT_MAX
#define eps 1e-8
#define MOD 20071027
using namespace std;
char s[MAX],t[MAX];
int ch[MAX][30],mark[MAX],dp[MAX],cnt;
void insert(){ //插入字符串
int n = strlen(t);
int u = 0;
for (int i=0; i<n; i++){
int c = t[i] - 'a';
if (!ch[u][c]){ //建一个新节点
memset(ch[++cnt],0,sizeof(ch[cnt]));
ch[u][c] = cnt;
}
u = ch[u][c];
}
mark[u] = n; //mark[]记录节点附加信息,此处当遇到字符串结尾时记录字符串长度。
}
void query(char* st, int l){ //查询操作
int n = strlen(st);
int u = 0;
for (int i=0; i<n; i++){
int c = st[i] - 'a';
if (ch[u][c]){
u = ch[u][c];
if (mark[u]) dp[l] = (dp[l] + dp[l+mark[u]]) % MOD; //如果mark[]不为0,则该节点为一个字符串的结尾节点
}
else break;
}
}
int main(){
int m,T = 0;
while(scanf("%s",s) != EOF){
T++;
memset(dp,0,sizeof(dp));
memset(mark,0,sizeof(mark));
memset(ch,0,sizeof(ch));
cnt = 0;
scanf("%d",&m);
for (int i=0; i<m; i++){
scanf("%s",t);
insert();
}
int n = strlen(s);
dp[n] = 1;
for (int i=n-1; i>=0; i--){
query(s+i,i);
}
printf("Case %d: %d\n",T,dp[0] % MOD);
}
return 0;
}