51nod 最长公共子序列测试 【LCS+回溯】
输入
copy
第1行:字符串A 第2行:字符串B (A,B的长度 <= 1000)
输出
copy
输出最长的子序列,如果有多个,随意输出1个。
输入示例
copy
abcicba abdkscab
输出示例
copy
abca
copy
#include <map> #include <set> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> #include <iostream> #include <stack> #include <cmath> #include <string> #include <vector> #include <cstdlib> //#include <bits/stdc++.h> //#define LOACL #define space " " using namespace std; //typedef long long Long; //typedef __int64 Int; typedef pair<int, int> paii; const int INF = 0x3f3f3f3f; const double ESP = 1e-6; const double PI = acos(-1.0); const int MOD = 1e9 + 7; const int MAXN = 1000 + 5; char str1[MAXN], str2[MAXN]; int dp[MAXN][MAXN], vis[MAXN][MAXN]; void print(int x, int y) { if (x == 0 || y == 0) return; if (vis[x][y] == 1) { print(x - 1, y - 1); printf("%c", str1[x - 1]); } else if (vis[x][y] == 2) { print(x - 1, y); } else { print(x, y - 1); } } int main() { while (scanf("%s%s", &str1, &str2) != EOF) { int cnt = 0, t = 0; int len1 = strlen(str1); int len2 = strlen(str2); memset(dp, 0, sizeof(dp)); memset(vis, 0, sizeof(vis)); for (int i = 1;i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (str1[i - 1] == str2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; vis[i][j] = 1; } else if (dp[i - 1][j] > dp[i][j - 1]){ dp[i][j] = dp[i - 1][j]; vis[i][j] = 2; } else { dp[i][j] = dp[i][j - 1]; vis[i][j] = 3; } } } print(len1, len2); printf("\n"); } return 0; }
本文作者: zprhhs
本文链接:https://www.cnblogs.com/cniwoq/p/6770799.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
标签:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
· SQL Server统计信息更新会被阻塞或引起会话阻塞吗?
· 本地部署 DeepSeek:小白也能轻松搞定!
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 如何基于DeepSeek开展AI项目