标签:
#include<iostream> using namespace std; void Print_LCS(int **b, string X, int i, int j) { if (i == 0 || j == 0) return; if (b[i][j] == 1) { Print_LCS(b, X, i - 1, j - 1); cout << X.at(i) << " "; } else if (b[i][j] == 0) { Print_LCS(b, X, i - 1, j); } else { Print_LCS(b, X, i, j - 1); } } void LCS_length(string X, string Y) { int m = X.length(); int n = Y.length(); X = "0" + X; Y = "0" + Y; int **b = new int*[m + 1]; for (int i = 0; i < m + 1; i++) { b[i] = new int[n + 1]; } int **c = new int*[m+1];//LCS的长度 for (int i = 0; i <=m; i++) { c[i] = new int[n+1]; } for (int i = 1; i <= m; i++) { c[i][0] = 0; } for (int j = 0; j <= n; j++) { c[0][j] = 0; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (X.at(i) == Y.at(j)) { c[i][j] = c[i - 1][j - 1] + 1; b[i][j] = 1; } else if (c[i - 1][j] >= c[i][j - 1]) { c[i][j] = c[i - 1][j]; b[i][j] = 0; } else { c[i][j] = c[i][j - 1]; b[i][j] = -1; } } } Print_LCS(b,X,m,n); cout << "\n"; } int main() { string X= "ABCBDAB"; string Y = "BDCABA"; LCS_length(X,Y); }
标签:
原文地址:http://www.cnblogs.com/liuhg/p/LCS.html