【算法导论实验4】动态规划-最长公共子序列LCS

来源:互联网 发布:ieye下载软件 编辑:程序博客网 时间:2024/05/18 03:12

真的很重要!!不管是面试还是实际应用还是acm比赛!

原理在dp中属于好理解的..

#include <iostream>#include <cstring>#include <string>using namespace std;int c[100][100];int b[100][100];int countlength=0;void LCS_Length (string x, string y){int m =x.size();int n =y.size();for (int i = 0; i <= m; i++)c[i][0] = 0;for (int i = 0; i <= n; i++)c[0][i] = 0;for (int i = 0; i < m; i++){for (int j = 0; j < n; j++){if (x[i] == y[j]){c[i + 1][j + 1] = c[i][j] + 1;b[i + 1][j + 1] = 0;}else if (c[i][j + 1] >= c[i + 1][j]){c[i + 1][j + 1] = c[i][j + 1];b[i + 1][j + 1] = 1;}else{c[i + 1][j + 1] = c[i + 1][j];b[i + 1][j + 1] = 2;}}}}void Print_LCS (string x, int i, int j){if ((i == 0) || (j == 0))return ;if (b[i][j] == 0){Print_LCS (x, i - 1, j - 1);cout << x[i - 1] << ' ';countlength++;}else if (b[i][j] == 1)Print_LCS (x, i -1, j);elsePrint_LCS (x, i, j - 1);}int main(){string x,y;while (cin >> x >> y){LCS_Length (x, y);Print_LCS (x, x.size(), y.size());cout << endl;cout<<"长度是:"<<countlength<<endl;}return 0;}


0 0