Description
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 (-231 <= Ai < 231 ) — 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 4
Sample Output
2
1 4
题意: 给两个数组,求最长公共递增子序列。
分析: dp[i,j]表示a串前i个字符,b串前j个字符组成的,并且以b[j]为结尾的最长的LCIS,
转移方程:
dp[i,j]=dp[i-1,j]; //a[i]与b[j]不等
dp[i,j]=max(dp[i-1,k])+1; (1<=k<=j-1) //a[i]与b[j] 相等
以上转移方程是O(n^3)时间复杂度
优化:
由于最外层循环是 i,第二层是 j,循环 j 的时候,实际上同时找出dp[i-1,k] 的最大值MAX
方法:循环 j 的同时,若a[i]>b[j],更新MAX (因为当且仅当a[i]>b[j]时,后边循环 j 时可能用到这个决策来转移)
若a[i] = b[j] 则用MAX+1更新 dp[i,j],记录路径。
#include<iostream>
#include<cstdio>
using namespace std;
int l1,l2,ans,a[505],b[505],c[505][505],pth[505][505],rd[505];
int main()
{
int ii,jj,tmp,len;
scanf("%d",&l1);
for(int i=1;i<=l1;i++)
scanf("%d",a+i);
scanf("%d",&l2);
for(int i=1;i<=l2;i++)
scanf("%d",b+i);
for(int i=1;i<=l1;i++)
{
int mx=0;
for(int j=1;j<=l2;j++)
{
c[i][j]=c[i-1][j];
if(b[j]<a[i]&&c[i-1][j]>mx)
mx=c[i-1][j],tmp=j;
if(a[i]==b[j])
c[i][j]=mx+1,pth[i][j]=tmp;
if(ans<c[i][j])
ans=c[i][j],ii=i,jj=j;
}
}
printf("%d\n",ans);
len=ans;
while(len)
{
if(pth[ii][jj])
{
rd[len--]=b[jj];
jj=pth[ii][jj];
}
ii--;
}
for(int i=1;i<=ans;i++)
printf("%d%c",rd[i],i==ans?'\n':' ');
return 0;
}