Greatest Common Increasing Subsequence
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 Source Northeastern Europe 2003, Northern Subregion |
题意:
给出两个序列a、b,求最长公共递增子序列。
思路:
dp[j]表示以b[j]结尾的LCIS的长度。
每次用a[i]去更新dp[j],则
if(a[i]==b[j]) dp[j]=max(dp[j],dp[k]); (1<=k
维护好k的值,那么就可以将复杂度降到O(n*m)了。
由于要记录路径,用一维的dp、pre不太好处理,我用的是二维的,递归输出路径。
思路来源:推荐
代码:
#include#include #include #include #include #include #include