给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的)。

比如两个串为:

abcicba

abdkscab

ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。

收起

输入

第1行:字符串A
第2行:字符串B
(A,B的长度 <= 1000)

输出

输出最长的子序列,如果有多个,随意输出1个。

输入样例

abcicba
abdkscab

输出样例

abca

思路就是先求最长公共子序列,然后再根据路径逆推,找到匹配点。

#include<iostream>
#include<queue>
#include<algorithm>
#include<set>
#include<cmath>
#include<vector>
#include<map>
#include<stack>
#include<bitset>
#include<cstdio>
#include<cstring>
//---------------------------------Sexy operation--------------------------// #define cini(n) scanf("%d",&n)
#define cinl(n) scanf("%lld",&n)
#define cinc(n) scanf("%c",&n)
#define cins(s) scanf("%s",s)
#define coui(n) printf("%d",n)
#define couc(n) printf("%c",n)
#define coul(n) printf("%lld",n)
#define speed ios_base::sync_with_stdio(0)
#define file freopen("input.txt","r",stdin);freopen("output.txt","w",stdout)
//-------------------------------Actual option------------------------------// #define Swap(a,b) a^=b^=a^=b
#define Max(a,b) a>b?a:b
#define Min(a,b) a<b?a:b
#define mem(n,x) memset(n,x,sizeof(n))
#define mp(a,b) make_pair(a,b)
//--------------------------------constant----------------------------------// #define INF 0x3f3f3f3f
#define maxn 1005
#define esp 1e-9
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
//------------------------------Dividing Line--------------------------------//
string a,b,ans;
int dp[maxn][maxn];
int main()
{
ans.clear();
cin>>a>>b;
a=' '+a;
b=' '+b;
int la=a.size();
int lb=b.size();
for(int i=1;i<la;i++)
{
for(int j=1;j<lb;j++)
{
if(a[i]==b[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
int m=la-1,n=lb-1;
while(dp[m][n])
{
if(dp[m][n]==dp[m-1][n]) m--;
else if(dp[m][n-1]==dp[m][n]) n--;
else
{
if(a[m]!=' ')
ans=a[m]+ans;
m--,n--;
}
}
cout<<ans<<endl;
}

最新文章

  1. nginx虚拟主机配置笔记
  2. httpwebrequest 请求压缩,接受压缩的字符流请求
  3. hdu 最大报销额
  4. eclipse中tomcat配置(待完善)
  5. ETL几种方案对比
  6. visual studio 2008安装报错问题处理
  7. 一张图讲解为什么需要自己搭建自己的git服务以及搭建的途径
  8. HDU 3584 Cube
  9. 【HTTP 2】简介(Introduction)
  10. BZOJ2733 [HNOI2012]永无乡 【线段树合并】
  11. html canvas-nest.js 源码
  12. Centos7编译opencv3.4.1
  13. easyui时的时间格式yyyy-MM-dd与yyyy-MM-ddd HH:mm:ss
  14. HDU - 1828 Picture
  15. nginx 配置 https 请求
  16. 利用altium怎么生成PDF及怎么1:1打印文档
  17. 关于单独使用ckfinder时去除版本号和提示信息的破解
  18. MySQL数据引擎InnoDB和MyISAM互相转换
  19. Win2019 显示 SMBV1 协议不安全的处理
  20. eclipse 按装lombok与注解说明

热门文章

  1. tornado的ORM
  2. 让 .NET 轻松构建中间件模式代码
  3. 计算机网络协议,UDP数据报的分析
  4. Django ORM操作数据库常用API
  5. 08-jmeter-plugins-manager.jar插件安装
  6. git获取特定的commit
  7. Tomcat5的web应用启动顺序详解
  8. HTTP 405 的错误提示:消息 JSP 只允许 GET、POST 或 HEAD。Jasper 还允许 OPTIONS 的解决方法
  9. linux下的信号量PV操作进阶之路
  10. react-devtools安装调试