描述
給定兩個整數序列,寫一個程式求它們的最長上升公共子序列,
當以下條件滿足的時候,我們將長度為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 ),第三行是長度N(1 <= M <= 500),第四行是該序列的N個整數Ai (-231 <= Ai < 231 )
輸出
在第一行,輸出兩個序列的最長上升公共子序列的長度L,在第二行,輸出該子序列,如果有不止一個符合條件的子序列,則輸出總和最小的一個,
樣例輸入
5
1 4 2 5 -12
4
-12 1 2 4
樣例輸出
2
1 4
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int n,m,q,k;
struct hehe{
int num;
vector<int>point;
}dp[505],tmp,ans;
int a[505],b[505];
int main(){
cin>>n;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
cin>>m;
for(int j=1;j<=m;j++)
scanf("%d",&b[j]);
for(int i=1;i<=m;i++){
tmp.num=0;
tmp.point.clear();
for(int j=1;j<=n;j++){
if(b[i]>a[j]&&dp[j].num>tmp.num)tmp=dp[j];
if(a[j]==b[i]){
dp[j]=tmp;
dp[j].num++;
dp[j].point.push_back(a[j]);
}
}
}
for(int i=1;i<=n;i++)if(dp[i].num>ans.num)ans=dp[i];
cout<<ans.num<<endl;
for(int k=0;k<ans.point.size();k++)
cout<<ans.point[k]<<" ";
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/376987.html
標籤:其他
