NOIP2015提高组Day2T2(子串)题解

文章目录

题目信息

题目传送门

解题思路

法1:三维dp(no优化,70pts&MLE)

  • 状态定义
    定义dpkij为从a的前i个字符中取k个互不重叠非空子串, 填充b的方案数。
  • 边界条件
    ∀dpi00 = 1
  • 状态转移
    对于每次转移,有以下两种情况(答案为两者之和):
条件 方案数
不使用ai dpki-1j
使用a1toi的前缀填b1toj的后缀 NOIP2015提高组Day2T2(子串)题解
  • 时间复杂度:O(nm3)
  • 空间复杂度:O(nm2)

这题真坑

法2:法1+滚动数组优化(80pts,TLE)

  • 可以发现dpkij的值在dp数组中只取决于dpk-1
  • 时间复杂度:O(nm3)
  • 空间复杂度:O(nm)

怎么还AC不了啊啊啊啊啊

法3:法2+前缀和优化(AC!!)

可以发现若axtoi = bytoj = 0,则ax2toi = by2toj = 0,所以可以用s数组维护dp条件前缀和(不要忘记开滚动数组优化哦)。

代码实现

法1

#include <bits/stdc++.h>
using namespace std;
const int N = 1005, M = 205, P = 1000000007;
int dp[N][M][M];
char a[N], b[M];
int main () {
    int n, m, k;
	cin >> n >> m >> k >> (a + 1) >> (b + 1);
	for (int i = 0; i <= n; ++i) {
		dp[i][0][0] = 1;
	}
	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= m && j <= i; ++j) {
			for (int k = 1, *p = &(dp[i][j][k] = dp[i - 1][j][k]); k <= M && k <= j; ++k, p = &(dp[i][j][k] = dp[i - 1][j][k])) {
				for (int x = i, y = j; x > 0 && y > 0 && a[x] == b[y]; --x, --y) {
					*p = (*p + dp[x - 1][y - 1][k - 1]) % P;
				}
			}
		}
	}
	cout << dp[n][m][k] << '\n';
	return 0;
}

法2

#include <bits/stdc++.h>
using namespace std;
const int N = 1005, M = 205, P = 1000000007;
int dp[2][N][M];
char a[N], b[M];
int main () {
    int n, m, K;
	cin >> n >> m >> K >> (a + 1) >> (b + 1);
	for (int i = 0; i <= n; ++i) {
		dp[0][i][0] = 1;
	}
	for (int k = 1, t = 1; k <= K; ++k, t = !t) {
		for (int i = k; i <= n; ++i) {
			for (int j = k; j <= i && j <= n; ++j) {
				int *p = &(dp[t][i][j] = dp[t][i - 1][j]);
				for (int x = i, y = j; x >= k && y >= k && a[x] == b[y]; --x, --y) {
					*p = (*p + dp[!t][x - 1][y - 1]) % P;
				}
			}
		}
	}
	cout << dp[K % 2][n][m] << '\n';
	return 0;
}

法3

#include <bits/stdc++.h>
using namespace std;
const int N = 1005, M = 205, P = 1000000007;
int dp[2][N][M], s[2][N][M];
char a[N], b[M];
int main () {
    int n, m, K;
	cin >> n >> m >> K >> (a + 1) >> (b + 1);
	for (int i = 0; i <= n; ++i) {
		dp[0][i][0] = s[0][i][0] = 1;
	}
	for (int i = 1; i ^ n; ++i) {
		for (int j = 1; j ^ m; ++j) {
			s[0][i][j] += (a[i] == b[j]) * s[0][i - 1][j - 1];
		}
	}
	for (int k = 1, t = 1; k <= K; ++k, t = !t) {
		memset(s[t], 0, sizeof s[t]);
		for (int i = k; i <= n; ++i) {
			for (int j = k; j <= i && j <= m; ++j) {
				int *p = &(dp[t][i][j] = dp[t][i - 1][j]);
				bool f = (a[i] == b[j] && i >= k && j >= k);
				*p = (*p + f * s[!t][i - 1][j - 1]) % P;
				s[t][i][j] = (*p + f * s[t][i - 1][j - 1]) % P;
			}
		}
	}
	cout << dp[K % 2][n][m] << '\n';
	return 0;
}
上一篇:[NOIP2015 普及组] 推销员


下一篇:NOIp2015 提高组 解题报告