其他分享
首页 > 其他分享> > NOIP2015提高组Day2T2(子串)题解

NOIP2015提高组Day2T2(子串)题解

作者:互联网

文章目录

题目信息

题目传送门

解题思路

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

条件方案数
不使用aidpki-1j
使用a1toi的前缀填b1toj的后缀在这里插入图片描述

这题真坑

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

怎么还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,int,题解,复杂度,Day2T2,--,&&,优化,dp
来源: https://blog.csdn.net/yueyuedog/article/details/119891232