Greatest Common Increasing Subsequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9049 Accepted Submission(s): 2912
Problem 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
Source
#include<stdio.h> #include<string.h> #include<math.h> #include<iostream> using namespace std; const int maxn=510; int a[maxn],f[maxn][maxn],b[maxn]; //We have to consider both the publicity of the longest substring and the ascending property. In essence, our state is different from the previous longest common subsequence. //In order to ensure the ascending property when the state is defined, our f[i][j] is actually the longest common ascending subsequence ending with a[i], b[j], int find(int i,int j) { int temp=0; for(int k1=1;k1<i;k1++) { for(int k2=1;k2<j;k2++) { if(a[k1]<a[i]&&b[k2]<b[j])//Complies with the rising condition { if(f[k1][k2]>temp) temp=f[k1][k2]; } } } return temp; } intmain() { int T; cin>>T; for(int t=1;t<=T;t++) { int n,m,maximum=-1; memset(f,0,sizeof(f)); // complete the data entry 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]); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { if(a[i]==b[j])//Only the same can start searching f[i][j]=find(i,j)+1; else f[i][j]=max(find(i-1,j),find(i,j-1)); if(f[i][j]>maximum) maximum=f[i][j]; } } cout<<maximum<<endl; if(t!=T) cout<<endl; } return 0; }