#include <stdio.h> #include <algorithm> #include <string.h> using namespace std; int n,m,a[505],b[505],dp[505][505]; int LICS() { int MAX,i,j; memset(dp,0,sizeof(dp)); for(i = 1; i<=n; i++) { MAX = 0; for(j = 1; j<=m; j++) { dp[i][j] = dp[i-1][j]; if(a[i]>b[j] && MAX<dp[i-1][j]) MAX = dp[i-1][j]; if(a[i]==b[j]) dp[i][j] = MAX+1; } } MAX = 0; for(i = 1; i<=m; i++) if(MAX<dp[n][i]) MAX = dp[n][i]; return MAX; }
优化成一维
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int a[505],b[505],dp[505],n,m; int LICS() { int i,j,MAX; memset(dp,0,sizeof(dp)); for(i = 1; i<=n; i++) { MAX = 0; for(j = 1; j<=m; j++) { if(a[i]>b[j] && MAX<dp[j]) MAX = dp[j]; if(a[i]==b[j]) dp[j] = MAX+1; } } MAX = 0; for(i = 1; i<=m; i++) if(MAX<dp[i]) MAX = dp[i]; return MAX; }
时间: 2024-10-07 15:13:38