Greatest Common Increasing Subsequence-最长公共上升子序列

Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

 Status

Description

This is a problem from ZOJ 2432.To make it easyer,you just need output the length of the subsequence.
 

Input

Each sequence is described with M - its length (1 <= M <= 500) and M integer numbers Ai (-2^31 <= Ai < 2^31) - the sequence itself.
 

Output

output print L - the length of the greatest common increasing subsequence of both sequences.
 

Sample Input

    
    
1 5 1 4 2 5 -12 4 -12 1 2 4
 

Sample Output

    
    
2
 认识到了最长公共上升子序列,我发现自己dp基础一塌糊涂,
后来仔细研究,终于明白它是怎么回事,下面介绍的代码
现在有两个字符串A[1.....n],B[1.....m]
dp[i][j]代表着A序列的前i个与以B[j]为结尾的最长公共上升子序列
这里我要说清楚,当时就是这里没有看明白,也许是自己文字理解能力不够,
这里就相当于是最长上升子序列一样,前i个不用将,以B[j]为结尾的意思是
就像最长上升子序列dp[i]=dp[j]+1,这里的意思是以i这个数结尾的最长上升子序列
上述的代表着A序列的前i个与以B[j]为结尾的最长公共上升子序列就是这个意思
然后就是不断更新了,用一个Max来记录比B[j]小的最长公共上升子序列
下面是代码中的细节讲解
Max=0;这里的意思是最开始的最长公共上升子序列都为零
for(int j=1; j<=m; j++) {
dp[i][j]=dp[i-1][j];将前i-1位置的值直接复制
if(A[i]>B[j])Max=max(dp[i-1][j],Max);这里的意思是如果A[i]>B[j]就要更新Max
为什么,因为最长上升子序列,这是为下面这一行代码做准备的,因为往后走时,如果存在A[i]==B[j]
那么,我必须要有小于B[j]的最长公共上升子序列,这里我们可以知道如果A[i]==B[j]那么上面那一行的代码
求到的Max不正是我要的吗,因为A[i]==B[j],所以上面那一行相当于是变成了B[k(k是某一个,肯定不会与上面的j相等)]>B[j]
那么上面的代码单独提出来
:(其中两个j是不相等的)if(B[j]>B[j])Max=max(dp[i-1][j],Max);不正是求解我需要的小于B[j]的最长公共上升子序列
如此所有的代码都变得非常合理了。
if(A[i]==B[j])dp[i][j]=Max+1;
}
/*
Author: 2486
Memory: 2416 KB		Time: 0 MS
Language: G++		Result: Accepted
VJ RunId: 4177842		Real RunId: 14209604
Public:		No Yes
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=500+5;
int A[maxn],B[maxn];
int dp[maxn][maxn];
int t,n,m;
int main() {
    scanf("%d",&t);
    while(t--) {
        scanf("%d",&n);
        for(int i=1; i<=n; i++)scanf("%d",&A[i]);
        scanf("%d",&m);
        for(int i=1; i<=m; i++)scanf("%d",&B[i]);
        int Max;
        memset(dp,0,sizeof(dp));
        for(int i=1; i<=n; i++) {
            Max=0;
            for(int j=1; j<=m; j++) {
                dp[i][j]=dp[i-1][j];
                if(A[i]>B[j])Max=max(dp[i-1][j],Max);
                if(A[i]==B[j])dp[i][j]=Max+1;
            }
        }
        Max=0;
        for(int i=1; i<=m; i++) {
            Max=max(Max,dp[n][i]);
        }
        printf("%d\n",Max);
        if(t)printf("\n");
    }
    return 0;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值