poj 2127 LCIS

Greatest Common Increasing Subsequence
Time Limit: 10000MS Memory Limit: 65536K
Total Submissions: 9179 Accepted: 2421
Case 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 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
 
和zoj2432 一样
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 505;
int num1[N],num2[N],dp[N][N];  //dp[i][j]表示以num1串的前i个字符b串的前j个字符且以num2[j]结尾构成的LCIS的长度
int path[N][N];   //用二维数组path[i][j]存储上个最长长度是以num2[]的哪个结尾的,
					//假设之前的最长长度是dp[i'][j'],则path[i][j] = j'。
int main()
  {
      int t,n,m;
     // cin>>t;
     while(cin>>n)  //case
     {
          
		 memset(path,0,sizeof(path));  
          for(int i=1;i<=n;i++)
			  cin>>num1[i];
          cin>>m;
          for(int j=1;j<=m;j++)
			  cin>>num2[j];
          memset(dp,0,sizeof(dp));
          int answer=0;
          int MAX,posj=0,I,J,lu[N];  //Lu记录LCIS结果的下标
          for(int i=1;i<=n;i++)
          {
              MAX=0;posj=0;
              for(int j=1;j<=m;j++)
              {
                  dp[i][j]=dp[i-1][j];
                  if(num1[i]>num2[j]&&dp[i-1][j]>MAX)
				 {
						MAX=dp[i-1][j];
						posj=j;         //记录上个最长长度是以num2[]的哪个结尾的
				  }
                  if(num1[i]==num2[j])
				 {
						dp[i][j]=MAX+1;   
						path[i][j]=posj;
				  }
				  if(answer<dp[i][j])
				  {
					  answer=dp[i][j];
					  I=i;
					  J=j;
				  }
              }
          }
          cout<<answer<<endl;
		  int len=answer;
		  if(answer>0)
			  lu[answer--]=J;
		  while(answer&&I&&J)
		  {
			  if(path[I][J]>0)
			  {
				  lu[answer--]=path[I][J];
				  J=path[I][J];
			  }
			  I--;
		  }
		  for(int i=1;i<=len;++i)
			  cout<<num2[lu[i]]<<" ";
		  cout<<endl;
		  
         // if(t!=0)
		//	  cout<<endl;
     }
     return 0;    
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值