You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal possible length.
Sequence S 1 , S 2 , . . . , S N of length N is called an increasing subsequence of a sequence A 1 , A 2 , . . . , A M of length M if there exist 1 <= i 1 < i 2 < . . . < i N <= M such that S j = A ij for all 1 <= j <= N , and S j < S j+1 for all 1 <= j < N .
Input
Sequence S 1 , S 2 , . . . , S N of length N is called an increasing subsequence of a sequence A 1 , A 2 , . . . , A M of length M if there exist 1 <= i 1 < i 2 < . . . < i N <= M such that S j = A ij for all 1 <= j <= N , and S j < S j+1 for all 1 <= j < N .
Each sequence is described with M --- its length (1 <= M <= 500) and M integer numbers A
i (-2
31 <= A
i < 2
31 ) --- the sequence itself.
Output
On the first line of the output file print L --- the length of the greatest common increasing subsequence of both sequences. On the second line print the subsequence itself. If there are several possible answers, output any of them.
Sample Input
5 1 4 2 5 -12 4 -12 1 2 4Sample Output
2 1 4
//#include<bits/stdc++.h>
#include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
const int N=500+10;
int a[N],b[N],f[N][N],pre[N][N];
int s[N];
int main(){
//freopen("in.txt","r",stdin);
int n,m;
cin>>n;
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
cin>>m;
for(int i=1;i<=m;i++)
scanf("%d",&b[i]);
for(int i=1;i<=n;i++){
int p=0;
for(int j=1;j<=m;j++){
f[i][j]=f[i-1][j];
if(a[i]>b[j]&&f[i-1][p]<f[i-1][j])
p=j;
if(a[i]==b[j])
f[i][j]=f[i-1][p]+1,pre[i][j]=p;
}
}
int mm=0,id=-1;
for(int i=1;i<=n;i++)
if(mm<f[n][i]){
mm=f[n][i];
id=i;
}
cout<<mm<<endl;
int x=n,y=id,k=0;
while(f[x][y]){
while(a[x]!=b[y]&&x)x--;
s[++k]=b[y];
y=pre[x][y];
}
for(int i=k;i>0;i--)
if(i==k)printf("%d",s[i]);
else printf(" %d",s[i]);
//fclose(stdin);
}