HDU5763 Another Meaning (kmp+dp)

HDU5763 Another Meaning

Mean

给定两个字符串\(A,B\)\(B\)会有两种表示意思,询问\(A\)最终有多少种表达方式。

\(T <= 30,|A| <= 100000,|B| <= |A|\)

Sol

\(KMP+DP\).

先做一遍\(B\)串的\(Next\),把\(A\)中所有出现\(B\)的位置标记上(结尾位置)

\(dp[i]\)表示前\(i\)位能有多少种表达方式.\(dp[0]=1\).

\(if(vis[i]==1)dp[i]=(dp[i-1]+dp[i-lenp])%mod\)

\(else \ dp[i]=dp[i-1]\).

最后直接输出\(dp[lent]\)即可。

Code

#include<bits/stdc++.h>
#define N 100005
using namespace std;
char t[N],p[N];
int next1[N];
typedef long long ll;
const int mod = 1e9+7;
int vis[N];
ll dp[N];
/*
KMP + dp
 */
void get_next(char p[],int lenp){
    int j=0;
    for(int i=2;i<=lenp;++i){
        while(j&&p[j+1]!=p[i])j=next1[j];
        if(p[j+1]==p[i])j++;
        next1[i]=j;
    }
}
void kmp(char t[],int lent,char p[],int lenp){
    int j=0;
    for(int i=1;i<=lent;++i){
        while(j&&p[j+1]!=t[i])j=next1[j];
        if(p[j+1]==t[i])j++;
        if(j==lenp){
            vis[i]=1;
            //cout<<i-lenp+1<<endl;//输出p在t中出现的位置
        }
    }
}
void print(int lenp){
    for(int i=1;i<=lenp;++i){
        cout<<next1[i]<<" ";
    }
}
int T;

int main(){
    scanf("%d",&T);
    int ca=0;
    while(T--){
        scanf("%s %s",t+1,p+1);
        int lent=strlen(t+1);
        int lenp=strlen(p+1);
        get_next(p,lenp);//预处理p的next数组
        memset(vis,0,sizeof vis);
        memset(dp,0,sizeof dp);
        dp[0]=1;
        kmp(t,lent,p,lenp);
        for(int i=1;i<=lent;++i){
            if(vis[i])dp[i]=(dp[i-1]+dp[i-lenp])%mod;
            else dp[i]=dp[i-1];
        }
        printf("Case #%d: %lld\n",++ca,dp[lent]);
    }
    return 0;
}
/*

 */
posted @ 2021-10-03 10:57  Qquun  阅读(32)  评论(0)    收藏  举报