poj 2127 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


【分析】

题意是给两个数组,求最长公共上升子序列(LCIS)的长度且记录路径

状态:dp[i][j]表示以s1串的前i个字符s2串的前j个字符且以s2[j]为结尾构成的LCIS的长度。

状态转移:当 s1[i-1]!=s2[j-1]时,按照lcs可知由2个状态转移过来,dp[i-1][j],dp[i][j-1],因为dp[i][j]是以s2[j]为结尾构成的LCIS的长度。所以s2[j-1]一定会包含在里面,所以舍去dp[i][j-1],只由dp[i-1][j] 转移过来。当s1[i-1]==s2[j-1],这时肯定要找前面s1[ii-1]==s2[jj-1]的最长且比s2[j-1]小的状态转移过来.

若s1[i-1]!=s2[j-1] 那么dp[i][j]=dp[i][j-1]

若s1[i-1]==s2[j-1] 那么dp[i][j]=MAX{dp[i-1][k]+1(0 < k < j),s2[k-1] < s2[j-1]};
这里有一步可以优化就是求上一层的最值,可以在更新的同时就求出来,这样就从o(n^3)优化到o(n^2);

mac来记录临时路径


【代码】

//poj 2127 Greatest Common Increasing Subsequence
#include<iostream>
#include<cstdio>
#include<cstring>
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
int n,m;
int mx,mac,ii,jj,ans,len;
int s1[501],s2[501],pre[501][501],dp[501][501],lu[501]; //pre:路径 
int main()
{
    int i,j,k;
    scanf("%d",&n);
    fo(i,0,n-1)
      scanf("%d",&s1[i]);
    scanf("%d",&m);
    fo(i,0,m-1)
      scanf("%d",&s2[i]);
    fo(i,1,n)
    {
        mx=0;
        fo(j,1,m)
        {
            int temp=dp[i][j]=dp[i-1][j];
            if(mx<temp && s1[i-1]>s2[j-1])
              mx=temp,mac=j;
            if(s1[i-1]==s2[j-1])
              dp[i][j]=mx+1,pre[i][j]=mac;
            if(ans<dp[i][j])
              ans=dp[i][j],ii=i,jj=j;
        }
    }
    printf("%d\n",ans);
    len=ans;
    lu[ans--]=jj-1;
    while(ans && ii && jj)
    {
        if(pre[ii][jj])
        {
            lu[ans--]=pre[ii][jj]-1;
            jj=pre[ii][jj];
        }
        ii--;
    }
    fo(i,1,len)
      printf("%d ",s2[lu[i]]);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值