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.
题意:给俩个数字序列,求这俩个最大公共上升序列。
分析:dp[j]表示在这个长度为j时最大公共序列,俩个for循环,如果a[i]==b[j] dp[j]=dp[j-1]+1,否则dp[j]=dp[j-1]
代码:
#include<stdio.h> #include<algorithm> #include<string.h> using namespace std; int t,n,m; int a[1010]; int b[1010]; int dp[1010]; int main() { scanf("%d",&t); while(t--) { scanf("%d",&n); for(int i=0;i<n;i++) scanf("%d",&a[i]); scanf("%d",&m); for(int i=0;i<m;i++) scanf("%d",&b[i]); memset(dp,0,sizeof(dp)); for(int i=0;i<n;i++) { int s=0; for(int j=0;j<m;j++) { if(a[i]>b[j]&&s<dp[j]) //a[i]>b[j]是为了保证当a[i]==b[j]能有dp[i][j]=s+1; s=dp[j]; if(a[i]==b[j]) dp[j]=s+1; } } int ans=-1; for(int i=0;i<m;i++) ans=max(ans,dp[i]); printf("%d\n",ans); if(t) printf("\n"); } }
HDU - 1423 J - Greatest Common Increasing Subsequence
最新推荐文章于 2019-07-28 22:32:24 发布