CF-163A Substring and Subsequence 字符串DP

Substring and Subsequence

題意

給出兩個字符串s,t,求出有多少對s的子串和t的子序列相等。c++

思路

相似於最長公共子序列的dp數組。數組

dp[i][j]表示s中以i爲結尾的子串和t中前j個的子序列相等的個數。spa

轉移的時候dp[i][j]=dp[i][j-1];code

若是s[i]==t[j]那麼dp[i][j]+=dp[i-1][j-1]+1;,1是s[i]自身做爲子串的狀況.字符串

最後統計dp[i][lent]的和get

代碼

#include<bits/stdc++.h>
#define pb push_back
using namespace std;
typedef long long ll;
const int N=1e5+10;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;

char s[N],t[N];
int dp[5050][5050];
int main()
{
    scanf("%s%s",s+1,t+1);
    int lens=strlen(s+1);
    int lent=strlen(t+1);
    int ans=0;
    for(int i=1; i<=lens; i++)
    {
        for(int j=1; j<=lent; j++)
        {
            dp[i][j]=dp[i][j-1];
            if(s[i]==t[j])
            {
                dp[i][j]+=dp[i-1][j-1]+1;
                dp[i][j]%=mod;
            }
        }
    }
    for(int i=1; i<=lens; i++)
    {
        ans+=dp[i][lent];
        ans%=mod;
    }
    printf("%d",ans);
    return 0;
}
相關文章
相關標籤/搜索