最长公共子上升序列

描述
给定两个整数序列,写一个程序求它们的最长上升公共子序列。
当以下条件满足的时候,我们将长度为N的序列S 1 , S 2 , . . . , S N 称为长度为M的序列A 1 , A 2 , . . . , A M的上升子序列:

存在 1 <= i 1 < i 2 < . . . < i N <= M ,使得对所有 1 <= j <=N,均有S j = A ij,且对于所有的1 <= j < N,均有S j < S j+1

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


这题有点复杂

不仅要求出最长公共上升子序列的长度,还要写出数

#include<iostream>
#include<vector>
#include<string.h>
using namespace std;
const int maxn=550;
struct ac{
    int len=0;
    vector<int> v;
};


int main()
{
    int a[maxn],b[maxn],m,n;
    ac dp[maxn];
    cin>>m;
    for(int i=1;i<=m;i++){
        cin>>a[i];
    }
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>b[i];
    }
    for(int i=1;i<=n;i++){
        ac temp;
        for(int j=1;j<=m;j++){
            if(b[i]>a[j]&&temp.len<dp[j].len){
                    temp=dp[j];
            }
            if(b[i]==a[j]){
                dp[j].len=temp.len+1;
                dp[j].v=temp.v;
                dp[j].v.push_back(b[i]);
            }
        }
    }
    ac ans=dp[1];
    for(int i=2;i<=m;i++){
        if(dp[i].len>ans.len){
            ans=dp[i];
        }
    }
    cout<<ans.len<<endl;
    for(int i=0;i<ans.v.size();i++){
        cout<<ans.v[i]<<" ";
    }
    cout<<endl;
    return 0;
}
ps.用a数组跟b数组比较的话,会WA,真是玄学<*__*>


猜你喜欢

转载自blog.csdn.net/henu_jizhideqingwa/article/details/80285896