- Time: 2016-05-09-21:12:54
- Title Number: [2016-05-09][51nod][1006 longest common sub-sequence LCS]
- Main topic: [2016-05-09][51nod][1006 longest common sub-sequence lcs].md
- Analysis: Dynamic Planning
- DP[I][J] Represents the length of the longest common subsequence of string A in the first position, string B at position J
- DP[I][J] = dp[i-1][j-1] + 1 if a[i] = = A[j]
- else dp[i][j] = = Max (Dp[i-1][j], dp[i][j-1]);
- The maximum length is dp[n][m], n is the length of a, m is the length of B
- To restore a string, just go back to the place where the dp[i][j] just started to change.
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 1E3 + 10;
char a[maxn],b[maxn],ans[maxn];
int dp[maxn][maxn];
int main(){
scanf ( "%s%s " , a + 1 b + 1 );
int n = strlen(a+1),m = strlen(b+1);
memset(dp,0,sizeof(dp));
for ( int i = 1 ; I <= n ++ i ) {
for(int j = 1 ; j <= m ; ++j){
if(a[i] == b[j]){
DP [ i ][ j = DP [ i - 1 ][ j - 1 + 1
}else dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
}
}
int cur = 0;
for ( int i = n j = m DP [ i ][ j ];-- i ,-- j //return to the place where the value was first updated
while ( DP [ i ][ j ] == DP [ i - 1 ][ j -- i
while ( DP [ i ][ j ] == DP [ i ][ j - 1 ]) -- j ;
ans[cur++] = a[i];
}
reverse(ans,ans+cur);
ans[cur] = ‘\0‘;
printf("%s\n",ans);
return 0;
}
From for notes (Wiz)
[2016-05-09][51nod][1006 longest common subsequence LCS]