51Nod 1006 最长公共子序列Lcs
1 #include<cstring> 2 #include<cstdio> 3 #include<iostream> 4 #include<algorithm> 5 using namespace std; 6 7 const int maxn = 1010; 8 char a[maxn], b[maxn]; 9 int f[maxn][maxn]; 10 string s; 11 12 int main() 13 { 14 scanf("%s", a + 1); 15 scanf("%s", b + 1); 16 int n = strlen(a + 1); 17 int m = strlen(b + 1); 18 for (int i = 1; i <= n; i++) 19 for (int j = 1; j <= m; j++) 20 { 21 if (a[i] == b[j]) f[i][j] = f[i - 1][j - 1] + 1; 22 else f[i][j] = max(f[i - 1][j], f[i][j - 1]); 23 } 24 //动态规划找LCS 25 int i = n, j = m; 26 while (i && j) 27 { 28 if (a[i] == b[j]) 29 { 30 s += a[i]; 31 i--; 32 j--; 33 } 34 else if (f[i][j] == f[i - 1][j]) 35 i--; 36 else 37 j--; 38 } 39 int len = s.length(); 40 for (int i = len - 1; i >= 0; i--) 41 printf("%c", s[i]); 42 return 0; 43 }