hdu 1423 Greatest Common Increasing Subsequence
Greatest Common Increasing SubsequenceTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2990 Accepted Submission(s): 935 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 1 5 1 4 2 5 -12 4 -12 1 2 4 Sample Output 2 最长公共上升子序列(LCIS) |
二维做法
#include <iostream>
#include <string>
#define maxn 1010
#define max(a, b) a > b ? a : b
using namespace std;
int a[maxn], b[maxn];
int dp[2][maxn], ans;
int main(){
int T, n1, n2;
scanf("%d", &T);
while ( T-- ){
memset( dp, 0, sizeof(dp) );
scanf("%d", &n1);
for ( int i = 1; i <= n1; i++ ){
scanf("%d", &a[i]);
}
scanf("%d", &n2);
for ( i = 1; i <= n2; i++ ){
scanf("%d", &b[i]);
}
ans = 0;
for ( i = 1; i <= n1; i++ ){
for ( int j = 1; j <= n2; j++ ){
if ( a[i] == b[j] ){
dp[i&1][j] = dp[(i-1)&1][j-1] + 1;
}
else if( a[i] > b[j] ){ //只从比自己小的数那里继承最优状态
dp[i&1][j] = max( dp[i&1][j-1], dp[(i-1)&1][j] );
}
if ( dp[i&1][j] > ans ){
ans = dp[i&1][j];
}
}
}
printf("%d\n", ans);
if ( T ){
printf("\n");
}
}
}
一维的做法
#include <iostream>
#include <string>
#define maxn 1010
//#define max(a, b) a > b ? a : b
using namespace std;
int a[maxn], b[maxn];
int dp[maxn], ans;
int main(){
int T, n1, n2;
scanf("%d", &T);
while ( T-- ){
memset( dp, 0, sizeof(dp) );
scanf("%d", &n1);
for ( int i = 1; i <= n1; i++ ){
scanf("%d", &a[i]);
}
scanf("%d", &n2);
for ( i = 1; i <= n2; i++ ){
scanf("%d", &b[i]);
}
ans = 0;
for ( i = 1; i <= n1; i++ ){
int max = 0; //保存比a[i]小的当最优状态
for ( int j = 1; j <= n2; j++ ){
if ( a[i] == b[j] ){
dp[j] = max + 1;
}
else if( a[i] > b[j] && dp[j] > max ){ //只从比自己小的数那里继承最优状态
max = dp[j];
}
if ( dp[j] > ans ){
ans = dp[j];
}
}
}
printf("%d\n", ans);
if ( T ){
printf("\n");
}
}
return 0;
}