POJ 2127 Greatest Common Increasing Subsequence

本文介绍了一种解决最长公共递增子序列问题的方法,通过动态规划的方式寻找两个整数序列之间的最长递增子序列。文章详细解释了状态定义、状态转移方程,并给出了一种优化的时间复杂度为O(n^2)的算法实现。

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


题意: 给两个数组,求最长公共递增子序列。

分析: dp[i,j]表示a串前i个字符,b串前j个字符组成的,并且以b[j]为结尾的最长的LCIS,
转移方程:
dp[i,j]=dp[i-1,j]; //a[i]与b[j]不等
dp[i,j]=max(dp[i-1,k])+1; (1<=k<=j-1) //a[i]与b[j] 相等
以上转移方程是O(n^3)时间复杂度
优化:
由于最外层循环是 i,第二层是 j,循环 j 的时候,实际上同时找出dp[i-1,k] 的最大值MAX
方法:循环 j 的同时,若a[i]>b[j],更新MAX (因为当且仅当a[i]>b[j]时,后边循环 j 时可能用到这个决策来转移)
若a[i] = b[j] 则用MAX+1更新 dp[i,j],记录路径。


#include<iostream>
#include<cstdio>
using namespace std;
int l1,l2,ans,a[505],b[505],c[505][505],pth[505][505],rd[505];
int main()
{
    int ii,jj,tmp,len;
    scanf("%d",&l1);
    for(int i=1;i<=l1;i++)
        scanf("%d",a+i);
    scanf("%d",&l2);
    for(int i=1;i<=l2;i++)
        scanf("%d",b+i);
    for(int i=1;i<=l1;i++)
    {
        int mx=0;
        for(int j=1;j<=l2;j++)
        {
            c[i][j]=c[i-1][j];
            if(b[j]<a[i]&&c[i-1][j]>mx)
                mx=c[i-1][j],tmp=j;
            if(a[i]==b[j])
                c[i][j]=mx+1,pth[i][j]=tmp;
            if(ans<c[i][j])
                ans=c[i][j],ii=i,jj=j;
        }
    }
    printf("%d\n",ans);
    len=ans;
    while(len)
    {
        if(pth[ii][jj])
        {
            rd[len--]=b[jj];
            jj=pth[ii][jj];
        }
        ii--;
    }
    for(int i=1;i<=ans;i++)
        printf("%d%c",rd[i],i==ans?'\n':' ');
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值