AcWing 897:最长公共子序列 ← 子序列问题(n≤1e3)
【题目来源】
https://www.acwing.com/problem/content/899/
【题目描述】
给定两个长度分别为 N 和 M 的字符串 A 和 B,求既是 A 的子序列又是 B 的子序列的字符串长度最长是多少。
【输入格式】
第一行包含两个整数 N 和 M。
第二行包含一个长度为 N 的字符串,表示字符串 A。
第三行包含一个长度为 M 的字符串,表示字符串 B。
字符串均由小写字母构成。
【输出格式】
输出一个整数,表示最大长度。
【输入样例】
4 5
acbd
abedc
【输出样例】
3
【数据范围】
1≤N,M≤1000
【算法分析】
● 本题问题规模为 1e3,所以采用如下经典动态规划方法求解是可行的。
● 若问题规模大于 1e3,采用本题代码将会导致 MLE 及 TLE。则问题规模大于 1e3 的“最长公共子序列”问题的代码详见:https://blog.csdn.net/hnjzsyjyj/article/details/149813893
【算法代码】
#include <bits/stdc++.h>
using namespace std;const int maxn=1e3+5;
char a[maxn],b[maxn];
int dp[maxn][maxn];int main() {int n,m;cin>>n>>m;int len=1;for(int i=1; i<=n; i++) cin>>a[i];for(int i=1; i<=m; i++) cin>>b[i];for(int i=1; i<=n; i++) {for(int j=1; j<=m; j++) {if(a[i]==b[j]) {dp[i][j]=max(dp[i-1][j-1]+1,dp[i][j]);} else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);}}cout<<dp[n][m];return 0;
}/*
in:
4 5
acbd
abedcout:
3
*/
【参考文献】
https://www.acwing.com/solution/content/8111/
https://mp.weixin.qq.com/s/ct5Mwf_h8dCn7zy1eHPfug
https://blog.csdn.net/hnjzsyjyj/article/details/100183820
https://blog.csdn.net/hnjzsyjyj/article/details/149798835
https://www.cnblogs.com/zhuzhucheng/p/16131615.html
https://blog.csdn.net/hnjzsyjyj/article/details/149813893