hdu6153 A Secret(KMP + DP)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43408238/article/details/102732395

Meaning of the questions: to give you two strings t and s, and then let you calculate the length of the suffix s number appears in t * suffix accumulated sum.

Ideas: 

Consider KMP, because KMP is matching prefix so, we need to reverse the string.

Dp is then set for the length of the array prefixed number i appearing in t, KMP during the matching, each dp [j] ++. However, in order to reduce the KMP backtracking algorithm, identical matches length of the character is omitted, i.e. Next [i] represents the maximum length of the non-prefix-suffix substring match the prefix string, if the Next [i] non-zero, the length I must contain a prefix length prefix match Next [i] and the entire string prefix.

即 dp[Next[i]] += dp[i]

 

AC Code:

#include<iostream>
#include<cstring>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<cstdio>
#include<iomanip>
#include<sstream>
#include<algorithm>

using namespace std;
#define read(x) scanf("%d",&x)
#define Read(x,y) scanf("%d%d",&x,&y)
#define sRead(x,y,z)  scanf("%d%d%d",&x,&y,&z)
#define gc(x)  scanf(" %c",&x);
#define mmt(x,y)  memset(x,y,sizeof x)
#define write(x) printf("%d\n",x)
#define INF 0x3f3f3f3f
#define ll long long
const ll mod = 1e9 + 7;
#define pdd pair<double,double>
const int N = 1e6+5;
int Next[N];
char s[N];
char t[N];
ll dp[N];
void kmp_pre(int m){
    int i = 0,j = Next[0] = -1;
    while(i < m){
        while(j != -1&& s[i] != s[j]) j = Next[j];
        Next[++i] = ++j;
    }
}
void kmp(int n,int m){
    kmp_pre(m);
    int i = 0,j= 0;
    while(i < n){
        while(j != -1&&t[i] != s[j]) j = Next[j];
        ++i,++j;
        dp[j]++;
    }
}
int main()
{
    int T;
    read(T);
    while(T--){
        mmt(dp,0);
        mmt(Next,0);
        scanf("%s%s",t,s);
        int n = strlen(t);
        int m = strlen(s);
        reverse(t,t+n);
        reverse(s,s+m);
        kmp(n,m);
        ll ans = 0;
        for(int i = m;i >= 1;--i){
            dp[Next[i]] += dp[i];
        }
        for(int i = 1;i <= m;++i){
            ans += dp[i] * i;
            ans %= mod;
        }
        cout<<ans<<endl;


     }
}

 

 

Guess you like

Origin blog.csdn.net/qq_43408238/article/details/102732395