前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >04:最长公共子上升序列

04:最长公共子上升序列

作者头像
attack
发布2018-04-12 11:58:36
6420
发布2018-04-12 11:58:36
举报
文章被收录于专栏:数据结构与算法

总时间限制: 10000ms内存限制: 65536kB描述给定两个整数序列,写一个程序求它们的最长上升公共子序列。

当以下条件满足的时候,我们将长度为N的序列S1 , S2 , . . . , SN 称为长度为M的序列A1 , A2 , . . . , AM的上升子序列:

存在 1 <= i1 < i2 < . . . < iN <= M ,使得对所有 1 <= j <=N,均有Sj = Aij,且对于所有的1 <= j < N,均有Sj < Sj+1。

输入每个序列用两行表示,第一行是长度M(1 <= M <= 500),第二行是该序列的M个整数Ai (-231 <= Ai < 231 )输出在第一行,输出两个序列的最长上升公共子序列的长度L。在第二行,输出该子序列。如果有不止一个符合条件的子序列,则输出任何一个即可。样例输入

代码语言:javascript
复制
5
1 4 2 5 -12
4
-12 1 2 4

样例输出

代码语言:javascript
复制
2
1 4

考虑到需要输出,
所以用vector来记录、】
代码语言:javascript
复制
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<algorithm>
 6 #include<vector>
 7 using namespace std;
 8 const int MAXN=3001;
 9 const int maxn=0x7fffff;
10 void read(int &n)
11 {
12     char c='+';int x=0;bool flag=0;
13     while(c<'0'||c>'9')
14     {c=getchar();if(c=='-')flag=1;}
15     while(c>='0'&&c<='9')
16     {x=x*10+c-48;c=getchar();}
17     flag==1?n=-x:n=x;
18 }
19 int a[MAXN],b[MAXN];
20 int n,m;
21 int pre[MAXN];
22 int tot;
23 struct node
24 {
25     int l;
26     vector<int>v;
27     node()
28     {
29         l=0;
30     
31     }
32 }dp[MAXN];
33 int main()
34 {
35     read(m);
36     for(int i=1;i<=m;i++)
37         read(a[i]);
38     read(n);
39     for(int i=1;i<=n;i++)
40         read(b[i]);
41     
42     for(int i=1;i<=n;i++)
43     {
44         node mx;
45         for(int j=1;j<=m;j++)
46         {
47             if(b[i]>a[j]&&dp[j].l>mx.l)
48                 mx=dp[j];
49             if(b[i]==a[j])
50             {
51                 dp[j].l=mx.l+1;
52                 dp[j].v=mx.v;
53                 dp[j].v.push_back(b[i]);
54             }
55         }
56     }
57     node ans=dp[1];
58     
59     for(int i=2;i<=m;i++)
60         if(dp[i].l>ans.l)
61             ans=dp[i];
62 
63     printf("%d\n",ans.l);
64     for(int i=0;i<ans.v.size();i++)
65         printf("%d ",ans.v[i]);
66 
67     return 0;
68 }
代码语言:javascript
复制
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-07-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档