G.subsequence 1(dp + 排列组合)

时间:2023-03-08 16:27:21

subsequence 1

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld

题目描述

You are given two strings s and t composed by digits (characters '0' ∼\sim∼ '9'). The length of s is n and the length of t is m. The first character of both s and t aren't '0'.
Please calculate the number of valid subsequences of s that are larger than t if viewed as positive integers. A subsequence is valid if and only if its first character is not '0'.
Two subsequences are different if they are composed of different locations in the original string. For example, string "1223" has 2 different subsequences "23".

Because the answer may be huge, please output the answer modulo 998244353.

输入描述:

The first line contains one integer T, indicating that there are T tests.

Each test consists of 3 lines.

The first line of each test contains two integers n and m, denoting the length of strings s and t.

The second line of each test contains the string s.

The third line of each test contains the string t.

* 1≤m≤n≤30001 \le m \le n \le 30001≤m≤n≤3000.
* sum of n in all tests ≤3000\le 3000≤3000.
* the first character of both s and t aren't '0'.

输出描述:

For each test, output one integer in a line representing the answer modulo 998244353.
示例1

输入

复制

3
4 2
1234
13
4 2
1034
13
4 1
1111
2

输出

复制

9
6
11

说明

For the last test, there are 6 subsequences "11", 4 subsequcnes "111" and 1 subsequence "1111" that are valid, so the answer is 11.

算法:dp + 排列组合

题意:给你两个字符串s和t。找出字符串s中多有多少个子串大于字符串t。

题解:dp的作用是计算字符串s的子串与字符串t相同长度时的数量,而下面那个循环式计算字符串s的子串长度大于字符串t时的数量,两者相加就是最终所求的数量

注意:杨辉三角就是按照组合数的性质来的,读者可以自行证明。

#include <iostream>
#include <cstdio>
#include <memory.h> using namespace std; const int maxn = ;
const int mod = ; typedef long long ll; ll C[maxn][maxn]; //以杨辉三角的形式来存取组合数,表示C(i, j)
ll dp[maxn][maxn]; //表示字符串s从第i个位置开始,字符串t从第j个位置开始,有多少个字串所匹配
char s[maxn], t[maxn]; int main() {
//预处理组合数
for(int i = ; i <= ; i++) {
for(int j = ; j <= i; j++) {
if(i == j || j == ) {
C[i][j] = ;
} else {
C[i][j] = (C[i - ][j - ] + C[i - ][j]) % mod;
}
}
}
int T;
scanf("%d", &T);
while(T--) {
int n, m;
scanf("%d %d", &n, &m);
scanf("%s %s", s + , t + );
for(int i = ; i < n + ; i++) {
for(int j = ; j < m + ; j++) {
dp[i][j] = ;
}
}
//从后往前推,这样便于计算数量
for(int j = m; j > ; j--) {
for(int i = n; i > ; i--) {
dp[i][j] = dp[i + ][j]; //把上一次记录的值加进来
if(s[i] == t[j]) { //当相同时,你就不需要算当前这两个相同的字符的值,并把上一次没有算那两个字符的值加进来
dp[i][j] = (dp[i][j] + dp[i + ][j + ]) % mod;
}
if(s[i] > t[j]) { //当大于时,你就需要找出需要填充的组合数
dp[i][j] = (dp[i][j] + C[n - i][m - j]) % mod;
}
}
}
ll ans = dp[][];
//下面这个循环是找出在s中大于字符串t长度的子串数量
for(int i = ; i <= n; i++) {
if(s[i] == '') { //当第一个字符为0时,不用计算
continue;
}
for(int j = m; j <= n; j++) { //每次需要添加m到n个字符
ans = (ans + C[n - i][j]) % mod;
}
}
cout << ans << endl;
}
return ;
}