标签:
【模板】最长递增公共子序列
二维
1 #include <stdio.h> 2 #include <algorithm> 3 #include <string.h> 4 using namespace std; 5 6 int n,m,a[505],b[505],dp[505][505]; 7 8 int LICS() 9 { 10 int MAX,i,j; 11 memset(dp,0,sizeof(dp)); 12 for(i = 1; i<=n; i++) 13 { 14 MAX = 0; 15 for(j = 1; j<=m; j++) 16 { 17 dp[i][j] = dp[i-1][j]; 18 if(a[i]>b[j] && MAX<dp[i-1][j]) 19 MAX = dp[i-1][j]; 20 if(a[i]==b[j]) 21 dp[i][j] = MAX+1; 22 } 23 } 24 MAX = 0; 25 for(i = 1; i<=m; i++) 26 if(MAX<dp[n][i]) 27 MAX = dp[n][i]; 28 return MAX; 29 }
优化成一维
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 using namespace std; 5 6 int a[505],b[505],dp[505],n,m; 7 8 int LICS() 9 { 10 int i,j,MAX; 11 memset(dp,0,sizeof(dp)); 12 for(i = 1; i<=n; i++) 13 { 14 MAX = 0; 15 for(j = 1; j<=m; j++) 16 { 17 if(a[i]>b[j] && MAX<dp[j]) 18 MAX = dp[j]; 19 if(a[i]==b[j]) 20 dp[j] = MAX+1; 21 } 22 } 23 MAX = 0; 24 for(i = 1; i<=m; i++) 25 if(MAX<dp[i]) 26 MAX = dp[i]; 27 return MAX; 28 }
标签:
原文地址:http://www.cnblogs.com/jeff-wgc/p/4472911.html