除了走到哪里,还要加状态表示当前节点和已经匹配的串
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<cmath> #include<vector> #include <set> #include <queue> #define ll long long #define ld long double #define lson l,m,rt<<1 #define pi acos(-1) #define rson m+1,r,rt<<1|1 #define fo(i,l,r) for(int i = l;i <= r;i++) #define fd(i,l,r) for(int i = r;i >= l;i--) #define mem(x) memset(x,0,sizeof(x)) #define eps 1e-8 using namespace std; const int maxn = 250,maxs = 5; const ll inf = 1e9; const ll mod = 1000000007; ll read() { ll x=0,f=1; char ch=getchar(); while(!(ch>=‘0‘&&ch<=‘9‘)) { if(ch==‘-‘)f=-1; ch=getchar(); }; while(ch>=‘0‘&&ch<=‘9‘) { x=x*10+(ch-‘0‘); ch=getchar(); }; return x*f; } struct Trie{ int nxt[maxn][maxs],fail[maxn],end[maxn]; int root,L; int newnode(){ for(int i = 0;i < maxs;i++) nxt[L][i] = -1; end[L++]=0; return L-1; } void init(){ L = 0; root = newnode(); } void insert(char buf[],int id){ int len = strlen(buf); int now = root; for(int i = 0;i < len;i++){ if(buf[i]==‘R‘)buf[i]=0; else buf[i]=1; if(nxt[now][buf[i]]==-1) nxt[now][buf[i]] = newnode(); now = nxt[now][buf[i]]; } end[now]|=id; } void build(){ queue<int> Q; fail[root] = root; for(int i = 0;i < maxs;i++) { if (nxt[root][i] == -1) { nxt[root][i] = root; } else { fail[nxt[root][i]] = root; Q.push((nxt[root][i])); } } while(!Q.empty()){ int now = Q.front(); Q.pop(); end[now] |= end[fail[now]]; for(int i = 0;i < maxs;i++){ if(nxt[now][i]==-1) { nxt[now][i] = nxt[fail[now]][i]; }else{ fail[nxt[now][i]] = nxt[fail[now]][i]; Q.push(nxt[now][i]); } } } } }ac; int n,m; char s[105]; int dp[105][105][250][4]; void gao(){ fo(i,0,n){ fo(j,0,m){ fo(k,0,ac.L){ fo(t,0,3) { dp[i][j][k][t] = 0; } } } } dp[0][0][0][0]=1; fo(i,0,n){ fo(j,0,m){ fo(k,0,ac.L-1){ fo(t,0,3){ dp[i][j+1][ac.nxt[k][0]][t|ac.end[ac.nxt[k][0]]] += dp[i][j][k][t]; dp[i+1][j][ac.nxt[k][1]][t|ac.end[ac.nxt[k][1]]] += dp[i][j][k][t]; dp[i][j+1][ac.nxt[k][0]][t|ac.end[ac.nxt[k][0]]] %= mod; dp[i+1][j][ac.nxt[k][1]][t|ac.end[ac.nxt[k][1]]] %= mod; } } } } ll ans = 0; fo(i,0,ac.L-1){ ans = (ans + dp[n][m][i][3]) % mod; } printf("%lld\n",ans); } int main() { int T=read(); while(T--){ ac.init(); m=read();n=read(); fo(i,1,2){ scanf("%s",s); ac.insert(s,i); } ac.build(); gao(); } return 0; }
原文:https://www.cnblogs.com/hyfer/p/11664628.html