zoukankan      html  css  js  c++  java
  • 04:最长公共子上升序列

    总时间限制: 
    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。在第二行,输出该子序列。如果有不止一个符合条件的子序列,则输出任何一个即可。
    样例输入
    5
    1 4 2 5 -12
    4
    -12 1 2 4
    样例输出
    2
    1 4

    考虑到需要输出,
    所以用vector来记录、】

     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
    ",ans.l);
    64     for(int i=0;i<ans.v.size();i++)
    65         printf("%d ",ans.v[i]);
    66 
    67     return 0;
    68 }
     
  • 相关阅读:
    在intent-filter中的配置
    利用asynchttpclient开源项目来把数据提交给服务器
    URL的应用
    ScrollView在布局中的作用
    android中传统的创建数据库
    for (Sms sms : smsLists){}
    Android中对文件的读写进行操作
    android中的5大布局
    android复制包需要修改的几个地方
    【Unity Tips】备忘录(扫盲篇)
  • 原文地址:https://www.cnblogs.com/zwfymqz/p/7202339.html
Copyright © 2011-2022 走看看