【POJ】1458 Common Subsequence
作者:互联网
最长公共子序列问题是动态规划的经典问题之一,对于长度分别为n和m的两个序列,若是最后一个元素是一样的,那么我们只需要看长度分别为n-1和m-1的两个序列,若是不一样,则需要比较长度分别为n-1和m的两个序列或者长度分别为n和m-1的两个序列哪个的公共子序列是最长的。
递归解法:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000 + 10;
char str1[N], str2[N];
int dp[N][N];
int Func(int n, int m){
if(dp[n][m] != -1) return dp[n][m];
int ans;
if(n == 0 || m == 0) ans = 0;
else{
if(str1[n] == str2[m]) ans = Func(n - 1, m - 1) + 1;
else ans = max(Func(n - 1, m), Func(n, m - 1));
}
dp[n][m] = ans;
return ans;
}
int main(){
while(scanf("%s%s", str1 + 1, str2 + 1) != EOF){ //从下标1开始输入
int n = strlen(str1 + 1);
int m = strlen(str2 + 1);
for(int i = 0; i <= n; i++){
for(int j = 0; j <= m; j++){
dp[i][j] = -1;
}
}
printf("%d\n", Func(n, m));
}
return 0;
}
递推解法:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 1000 + 10;
char str1[N], str2[N];
int dp[N][N];
int main(){
while(scanf("%s%s", str1 + 1, str2 + 1) != EOF){ //从下标1开始输入
int n = strlen(str1 + 1);
int m = strlen(str2 + 1);
for(int i = 0; i <= n; i++){
for(int j = 0; j <= m; j++){
dp[i][j] = -1;
}
}
for(int i = 0; i <= n; i++){
for(int j = 0; j <= m; j++){
if(i == 0 || j == 0) dp[i][j] = 0;
else{
if(str1[i] == str2[j]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
printf("%d\n", dp[n][m]);
}
return 0;
}
标签:int,str2,str1,Subsequence,POJ,ans,include,1458,dp 来源: https://blog.csdn.net/weixin_55267022/article/details/122831455