POJ2127:Greatest Common Increasing Subsequence(LICS)

Description

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

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 4

Sample Output

2
1 4
 
题意:求最长递增公共子序列
思路:这题与杭电那道题是一样的,区别就在于这道题需要将该序列输出,这就牵涉到了路径记录的问题
 

#include <stdio.h> #include <string.h> #include <algorithm> using namespace std;

int a[505],b[505],dp[505],n,m,cnt; int mark[505][505],ans[505];

int LICS() {     int i,j,MAX,k;     memset(dp,0,sizeof(dp));     memset(mark,0,sizeof(mark));     for(i = 1; i<=n; i++)     {         memcpy(mark[i],mark[i-1],sizeof(mark[0]));         k = 0;         for(j = 1; j<=m; j++)         {             if(a[i-1]>b[j-1] && dp[k]<dp[j])                 k = j;             if(a[i-1]==b[j-1] && dp[k]+1>dp[j])             {                 dp[j] = dp[k]+1;                 mark[i][j] = i*(m+1)+k;;             }         }     }     MAX = 0;     for(i = 1; i<=m; i++)         if(dp[MAX]<dp[i])             MAX = i;     i = m*n+n+MAX;     for(j = dp[MAX];j>0;j--)     {         ans[j-1] = b[i%(m+1)-1];         i = mark[i/(m+1)][i%(m+1)];     }     return dp[MAX]; }

int main() {     int i,k;     while(~scanf("%d",&n))     {         for(i = 0; i<n; i++)             scanf("%d",&a[i]);         scanf("%d",&m);         for(i = 0; i<m; i++)             scanf("%d",&b[i]);         cnt = 0;         k = LICS();         printf("%d\n",k);         for(i = 0;i<k;i++)         {             if(i)             printf(" ");             printf("%d",ans[i]);         }         printf("\n");     }

    return 0; }

你可能感兴趣的:(POJ2127:Greatest Common Increasing Subsequence(LICS))