lcs
来源:互联网 发布:监管资本 知乎 编辑:程序博客网 时间:2024/05/02 04:19
LCS打印出最大值和所有LCS
#include <iostream>#include <cstring>using namespace std;char str1[200],str2[200];//存放两个字符串int len[200][200];// len[i][j] 表示 str1[0..i] str2[0..j]的最大子序列长度int b[200][200];// b[i][j] 表示 求len[i][j]时,是哪种情况:0表示str1[i]==str2[j],1表示len[i][j] = len[i-1][j],-1表示len[i][j] = len[i][j-1]/*len[i][j] = max(len[i-1][j],len[i][j-1]); 当str[0][i] != str[1][j]*/int max(int a,int b){ return a>b?a:b;}int LCS(){int m = strlen(str1);int n = strlen(str2);int i,j;for (i=0;i<m ;i++ ){ len[i][0] = 0;}for (i=0;i<n ;i++ ){len[0][i] = 0;}for (i=1;i<=m ;i++ ){for (j=1;j<=n ;j++ ) // i,j下标从小到大,表示自底向上求len[i][j]的{if (str1[i-1] == str2[j-1]){len[i][j] = len[i-1][j-1]+1;b[i][j] = 0;}else if (len[i-1][j]>=len[i][j-1]){len[i][j] = len[i-1][j];b[i][j] = 1;}else{len[i][j] = len[i][j-1];b[i][j] = -1;}//len[i][j] = max(len[i-1][j],len[i][j-1]);}}/*for (i=0;i<=m ;i++ ){for (j=0;j<=n ;j++ ) // i,j下标从小到大,表示自底向上求len[i][j]的{cout << len[i][j] << " ";}cout << endl;}*/return len[m][n];}void print_lcs(int x,int y) // 打印str1[0...x]到str2[0...y]的最长子序列{if (x==0||y==0){return;}else if (b[x][y] == 0){print_lcs(x-1,y-1);cout << str1[x-1]<<" ";}else if (b[x][y] == 1){print_lcs(x-1,y);}else{print_lcs(x,y-1);}}int main(int argc, char *argv[]){freopen("1042.data","r",stdin);while ( cin >> str1 >> str2){cout << "size is: "<<LCS() << "\t";print_lcs(strlen(str1),strlen(str2));cout <<endl;memset(str1,0,sizeof(str1));memset(str2,0,sizeof(str2));memset(len,0,sizeof(len));}return 0;}