- 题目链接:http://codeforces.com/problemset/problem/163/A
- 题意:给你两个字符串——s , t 。要算s的子串(连续)和t的子序列(可不连续)相同的匹配数
- 算法:dp
- 思路:dp[i+1][j+1] 表示 “以s[i]为右端点的所有子串” 与 “t[0~ j] 区间内所有的子序列” 相同匹配的数量。
- 则状态转移方程为 dp[i+1][j+1] = dp[i+1][j] + ( t[j] ==s[i] )*( dp[i][j]+1);
- 等式右边的表示:
- “以s[i]为右端点的所有子串” 与 “t[0~ j-1] 区间内所有子序列” 相同匹配的数量 +
- “以s[i]为右端点的所有子串” 与 “以t[j]为右端点的所有子序列” 相同匹配的数量
- 因右端均固定,则第二项可化为
-右端点的匹配情况 乘( “以s[i-1]为右端点的所有子串” 与 “t[0~ j-1] 区间内所有子序列” 相同匹配的数量 + 1)
#include <bits/stdc++.h>
#define pi acos(-1)
#define fastcin ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL ll_INF = 0x3f3f3f3f3f3f3f3f;
const int maxn =5000 + 10;
const LL mod = 1e9+7;
string s, t;
int dp[maxn][maxn];
int main()
{
fastcin;
cin >> s >> t;
for(int i=0; i<s.size(); i++){
for(int j=0; j<t.size(); j++){
dp[i+1][j+1] = ( dp[i+1][j] + (s[i]==t[j])*(dp[i][j]+1) ) %mod;
}
}
int ans = 0, loc=t.size();
for(int i=0; i<s.size(); i++) ans = ( ans + dp[i+1][loc] )%mod;
cout << ans << endl;
}