《算法设计与分析》P56
1 #include<iostream> 2 #include<cstdlib> 3 using namespace std; 4 5 void LCSLength(int m, int n, char *x, char *y, int c[][10], int b[][10]) //定义函数时,**c,**b不会用 6 { 7 int i, j; 8 for(i = 1; i <= m; ++i){ 9 c[i][0] = 0; 10 b[i][0] = 0;//可以不用初始化 11 } 12 for(i = 1; i <= m; ++i){ 13 c[0][i] = 0; 14 b[0][i] = 0;//可以不用初始化 15 } 16 c[0][0] = b[0][0] = 0; 17 18 for(i = 1; i <= m; i ++)//m行n列 19 for(j = 1; j <= n; j ++){ 20 if(x[i] == y[j]){ 21 c[i][j] = c[i - 1][j - 1] + 1;//左上方 22 b[i][j] = 1; 23 }else if(c[i - 1][j] >= c[i][j - 1]){ 24 c[i][j] = c[i - 1][j];//上方 25 //X少去一项不影响,故最长公共子序列最后一项来自Y 26 //X(i)与Y(j)的最长公共子序列为X(i-1)与Y(j)最长公共子序列 27 //max{c[i][j-1], c[i-1][j]} 28 b[i][j] = 2; 29 }else{ 30 c[i][j] = c[i][j - 1]; //左方 31 //Y少去一项不影响,故最长公共子序列最后一项来自X 32 b[i][j] = 3; 33 } 34 } 35 } 36 37 void LCS(int i, int j, char *x, int b[][10]) 38 { 39 if(i == 0 || j == 0)return;//不会再有左上方,故该元素为公共子列的首元素 40 if(b[i][j] == 1){ 41 LCS(i - 1, j - 1, x, b);//从左上方来的 42 cout<<x[i];//先递归再打印 43 }else if(b[i][j] == 2)//X少去一项不影响,故X(i)与Y(j)的最长公共子序列为X(i-1)与Y(j)最长公共子序列 44 LCS(i - 1, j, x, b);//从上方来的 45 else 46 LCS(i, j - 1, x, b);//从左方来的 47 } 48 49 int main() 50 { 51 int b[10][10], c[10][10], i, j; 52 char X[9] = " ABCBDAB";//" dbcdabd"; 注意X[0]为空项 53 char Y[8] = " BDCABA";//" bacdbd"; 54 char Z[7]; 55 LCSLength(7, 6, X, Y, c, b);//LCSLength(7, 6, X, Y, &c[0], &b[0]); 56 cout<<c[7][6]<<endl; 57 for(i = 0; i <= 7; i ++){ 58 for(j = 0; j <= 6; j ++){ 59 cout<<c[i][j]<<" "; 60 } 61 cout<<endl; 62 } 63 cout<<endl; 64 for(i = 0; i <= 7; i ++){ 65 for(j = 0; j <= 6; j ++){ 66 cout<<b[i][j]<<" "; 67 } 68 cout<<endl; 69 } 70 LCS(7, 6, X, b);//LCS(7, 6, X, &b[0]); 71 system("pause"); 72 }