【POJ】1458 Common Subsequence
2022/2/8 23:22:30
本文主要是介绍【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; }
这篇关于【POJ】1458 Common Subsequence的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升