动态规划求最长公共子序列源程序
参考算法导论,得出源程序如下:
// //动态规划法求最长公共子序列,参考算法导论15.4 // #include<iostream> #include <vector> using namespace std; void lcs_length(const vector<char>& X, const vector<char>& Y, vector<vector<int> >& c, vector<vector<char> >& b) //X[1..m],Y[1..n],c[0..m,0..n],b[1..m][1..n],故要经过相应的转换 { int i=0,j=0; int m = X.size(); int n = Y.size(); for (i=1; i<=m; ++i) c[i][0] = 0; for (j=0; j<=n; ++j) c[0][j] = 0; for (i=1; i<=m; ++i) for (j=1; j<=n; ++j) { if (X[i-1] == Y[j-1]) { c[i][j] = c[i-1][j-1]+1; b[i-1][j-1] = 'x'; } else if (c[i-1][j] >= c[i][j-1]) { c[i][j] = c[i-1][j]; b[i-1][j-1] = 'u'; } else { c[i][j] = c[i][j-1]; b[i-1][j-1] = 'l'; } } } void print_lcs(const vector<vector<char> >& b, const vector<char> X, int i, int j) { if (-1==i ||0 ==-1) return; if ('x' == b[i][j]) { print_lcs(b,X,i-1,j-1); cout << X[i]; } else if ('u' == b[i][j]) print_lcs(b,X,i-1,j); else print_lcs(b,X,i,j-1); } int main() { vector<char> X, Y; vector<vector<int> > c; vector<vector<char> >b; //注意,这里两个尖括号之间要有空格,不然会被认为是符号">>" int i=0, j=0, m=0, n=0; cin >> m >> n; X.resize(m); Y.resize(n); b.resize(m); c.resize(m+1); cout << "input the element of X" << endl; for (i=0; i<m; ++i) { cin >> X[i]; b[i].resize(n); c[i].resize(n+1); } c[m].resize(n+1); cout << "input the element of Y" << endl; for (i=0; i<n; ++i) cin >> Y[i]; lcs_length(X,Y,c,b); for (i=0; i<=m; ++i){ for (j=0; j<=n; ++j) cout << c[i][j] <<' '; cout << endl; } cout << endl; for (i=0; i<m; ++i){ for (j=0; j<n; ++j) cout << b[i][j] <<' '; cout << endl; } print_lcs(b,X,m-1,n-1); cout << endl; return 0; }