【BZOJ2061】—Country(Kmp+记忆化搜索)
考虑匹配的过程就相当于,不过比较特殊
遇到大写字母就递归匹配
处理出表示串从匹配串第为开始匹配的匹配个数
则表示把串匹配完时指针所在位置
代码也比较好写
#include<bits/stdc++.h>
using namespace std;
const int RLEN=1<<20|1;
inline char gc(){
static char ibuf[RLEN],*ib,*ob;
(ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ib==ob)?EOF:*ib++;
}
#define gc getchar
inline int read(){
char ch=gc();
int res=0,f=1;
while(!isdigit(ch))f^=ch=='-',ch=gc();
while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
return f?res:-res;
}
#define pii pair<int,int>
#define pb push_back
#define re register
#define fi first
#define se second
#define ll long long
const int mod=10000;
const int N=30,L=105;
inline void add(int &a,int b){(a+=b)>=mod?a-=mod:0;}
int now,f[N][L],pos[N][L],vis[N][L],len[N],nxt[L],n,m;
char s[L],a[N][L];
inline bool iscap(char s){
return s>='A'&&s<='Z';
}
inline void dfs(int u,int p){
if(vis[u][p])return ;
int j=p;
for(int i=1;i<=len[u];i++)
if(iscap(a[u][i])){
int v=a[u][i]-'A';
dfs(v,j),add(f[u][p],f[v][j]),j=pos[v][j];
}
else{
while(j>0&&s[j+1]!=a[u][i])j=nxt[j];
if(s[j+1]==a[u][i])j++;
if(j==m)add(f[u][p],1),j=nxt[j];
}
vis[u][p]=1,pos[u][p]=j;
}
int main(){
n=read();
scanf("%s",s+1),now=s[1]-'A';
for(int i=1;i<=n;i++){
scanf("%s",s+1);
int id=s[1]-'A';
len[id]=strlen(s+1)-2;
for(int j=1;j<=len[id];j++)a[id][j]=s[j+2];
}
scanf("%s",s+1),m=strlen(s+1);
for(int i=0,j=2;j<=m;j++){
while(i>0&&s[i+1]!=s[j])i=nxt[i];
if(s[i+1]==s[j])i++;
nxt[j]=i;
}
dfs(now,0);
cout<<f[now][0]<<'\n';
}