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

来源:互联网 发布:淘宝查关键词排名 编辑:程序博客网 时间:2024/05/16 13:52
Greatest Common Increasing Subsequence
Time Limit: 1000MS Memory Limit: 32768KB 64bit IO Format: %I64d & %I64u

Submit 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

151 4 2 5 -124-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: 2486Memory: 2416 KBTime: 0 MSLanguage: G++Result: AcceptedVJ RunId: 4177842Real RunId: 14209604Public: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 0
原创粉丝点击