163A - Substring and Subsequence
令dp[i][j]表示,s字符串第i个结尾的所有字串,和t字符串[1,2,3,...,j]所有的子序列的匹配数量。
dp[i][j]=dp[i][j-1]
dp[i][j]+=(s[i]==s[j])?dp[i-1][j-1]+1:0
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<bitset>
#include<map>
//#include<regex>
#include<cstdio>
#include <iomanip>
#pragma GCC optimize(2)
#define up(i,a,b) for(int i=a;i<b;i++)
#define dw(i,a,b) for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
typedef unsigned long long ull;
const double esp = 1e-6;
const double pi = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int inf = 1e9;
using namespace std;
ll read()
{
char ch = getchar(); ll x = 0, f = 1;
while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
typedef pair<int, int> pir;
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define lrt root<<1
#define rrt root<<1|1
const int N = 5e3 + 10;
int dp[N][N];
char s[N], t[N];
const int mod = 1000000007;
ll add(ll x, ll y)
{
return x + y >= mod ? x + y - mod : x + y;
}
int main()
{
cin >> s + 1 >> t + 1;
int n = strlen(s + 1); int m = strlen(t + 1);
upd(i, 1, n)
{
upd(j, 1, m)
{
if (s[i] == t[j])
{
dp[i][j] = add(dp[i][j - 1], dp[i - 1][j - 1]);
dp[i][j] = add(dp[i][j], 1);
}
else
{
dp[i][j] = dp[i][j - 1];
}
}
}
ll ans = 0;
upd(i, 1, n)ans = add(ans, dp[i][m]);
cout << ans<<endl;
return 0;
}
橙橙橙