Greatest Common Increasing Subsequence
题目链接
You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal
possible length.
Sequence S1, S2, …, SN of length N is called an increasing subsequence of a sequence A1, A2, …, AM of length M if there exist 1 <= i1 < i2 < …< iN <= M such that Sj = Aij for all 1 <= j <= N, and Sj < Sj+1 for all 1 <= j < N.
Input
Each sequence is described with M - its length (1 <= M <= 500) and M integer numbers Ai (-2^31 <= Ai < 2^31) - the sequence itself.
Output
On the first line of the output 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.
This problem contains multiple test cases!
The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Sample Input
1
5
1 4 2 5 -12
4
-12 1 2 4
Sample Output
2
1 4
题目大意
让我们求最长公共上升子序列 输出个数 并且 输出一种情况(情况有多种输出一种即可)
最长公共上升子序列的详解
代码实现
#include<string>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<math.h>
using namespace std;
const int maxn=505;
int dp[maxn][maxn];
int pre[maxn][maxn]; //路径保存到达这个点前要达到的点,这道题我们从后往前存储
int main()
{
int t;
cin>>t;
while(t--)
{
int alen,blen;
int a[maxn],b[maxn];
cin>>alen;
for(int i=1;i<=alen;i++)
{
scanf("%d",&a[i]);
}
cin>>blen;
for(int i=1;i<=blen;i++)
{
scanf("%d",&b[i]);
}
memset(dp,0,sizeof(dp));
memset(pre,-1,sizeof(pre));
for(int i=1;i<=alen;i++)
{
int maxx=0;
int u=0;
for(int j=1;j<=blen;j++)
{
dp[i][j]=dp[i-1][j];
if(a[i]>b[j]&&maxx<dp[i-1][j])
{
maxx=dp[i-1][j];
u=j;
}
if(a[i]==b[j])
{
dp[i][j]=maxx+1;
pre[i][j]=u;
}
}
}
int z=1;
for(int i=1;i<=blen;i++)
{
if(dp[alen][i]>dp[alen][z])
z=i;
}
cout<<dp[alen][z]<<endl;
if(dp[alen][z]==0) continue;
int shuchu[maxn];
int cnt=1;
for(int i=alen;i>=1;i--)
{
if(pre[i][z]!=-1)
{
shuchu[cnt++]=a[i];
z=pre[i][z];
}
}
for(int i=cnt-1;i>=1;i--)
cout<<shuchu[i]<<" ";
cout<<endl;
}
}