POJ2127 Greatest Common Increasing Subsequence (LICS)

来源:互联网 发布:yankee 知乎 编辑:程序博客网 时间:2024/05/20 20:21

Greatest Common Increasing Subsequence
Time Limit: 10000MS Memory Limit: 65536KTotal Submissions: 11617 Accepted: 3040Case Time Limit: 2000MS Special Judge

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

51 4 2 5 -124-12 1 2 4

Sample Output

21 4

Source

Northeastern Europe 2003, Northern Subregion


思路:最长递增公共子序列题目,要输出最长子序列。

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm> using namespace std;int n,m,a[505],b[505],dp[505],mark[505][505],ans[505];int LICS(){int MAX,k;for(int i = 1; i <= n; i ++){k = 0;memcpy(mark[i],mark[i - 1],sizeof(mark[0]));for(int 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(int i = 1; i <= m; i ++)if(dp[i] > dp[MAX])MAX = i;int i = (m + 1) * n + MAX;for(int 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(){scanf("%d",&n);for(int i = 0; i < n; i ++)scanf("%d",&a[i]); scanf("%d",&m);for(int i = 0; i < m; i ++)scanf("%d",&b[i]);memset(dp,0,sizeof(dp));memset(ans,0,sizeof(ans));int k = LICS();printf("%d\n",k);for(int i = 0; i < k; i ++){if(i)printf(" ");printf("%d",ans[i]);}return 0;}


0 0
原创粉丝点击