CF-163A Substring and Subsequence 字符串DP

Substring and Subsequence

题意

给出两个字符串s,t,求出有多少对s的子串和t的子序列相等。

思路

类似于最长公共子序列的dp数组。

dp[i][j]表示s中以i为结尾的子串和t中前j个的子序列相等的个数。

转移的时候dp[i][j]=dp[i][j-1];

如果s[i]==t[j]那么dp[i][j]+=dp[i-1][j-1]+1;,1是s[i]自身作为子串的情况.

最后统计dp[i][lent]的和

代码

#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;
}

原文地址:https://www.cnblogs.com/valk3/p/12829355.html