最长公共子序列

来源:互联网 发布:优衣库 淘宝 代购 编辑:程序博客网 时间:2024/05/16 17:32

求最长公共子序列的长度:

if A[n] == B[m]

LCS_len(A[1...n], B[1...m]) = LCS_len(A[1...n-1], B[1...m-1]) + 1

 if A[n] != B[m]

LCS_len(A[1...n], B[1...m]) = max{ LCS_len(A[1...n], B[1...m-1]) , LCS_len(A[1...n-1], B[1...m])}

<pre name="code" class="cpp">// LCS.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stdio.h>#include <string>#include <vector>#include <iostream>#define MAX(a,b) (a) > (b) ? (a) : (b)using namespace std;int LCS_len(string str1, string str2, int i1, int i2){if(i1 < 0 || i2 < 0){return 0;}if(str1[i1] == str2[i2]){return LCS_len(str1, str2, i1-1, i2-1) + 1;}else{return MAX(LCS_len(str1, str2, i1-1, i2), LCS_len(str1, str2, i1, i2-1));}}int main(){string str1, str2;int common_len;cin >> str1;cin >> str2;common_len = LCS_len(str1, str2, str1.length()-1, str2.length()-1);printf("the common length is %d\n", common_len);while(1);}



求最长公共子序列见July博客

打印出所有的最长子序列

// LCS_sequence.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stdio.h>#include <string.h>//#include <iostream>#include <memory.h>//using namespace std;#define MAX_LEN 30void display(int **direction, int i, int j, const char str[]){if(i == 0 || j == 0){return;}if(direction[i][j] == 1){display(direction, i-1, j-1, str);printf("%c", str[i-1]);}else if(direction[i][j] == 2){display(direction, i, j-1, str);}else{display(direction, i-1, j, str);}}int main(){char str1[MAX_LEN];char str2[MAX_LEN];scanf("%s", str1);scanf("%s", str2);int str1_len, str2_len;str1_len = strlen(str1);str2_len = strlen(str2);int i, j;int ** count;int ** direction;//为1表示又direction[i][j]由direction[i-1][j-1]求得,2表示由左边求得,3表示由上面求得count = new int *[str1_len+1];direction = new int *[str2_len+1];for(i = 0; i <= str1_len; i++){count[i] = new int [str2_len + 1];memset(count[i], 0, sizeof(int)*(str2_len+1));}for(i = 0; i <= str1_len; i++){direction[i] = new int [str2_len + 1];memset(direction[i], 0, sizeof(int)*(str2_len+1));}for(i = 1; i <= str1_len; i++){for(j = 1; j <= str2_len; j++){if(str1[i-1] == str2[j-1])//由于字符串的下标是从0开始的{count[i][j] = count[i-1][j-1] + 1;direction[i][j] = 1;}else{if(count[i-1][j] >= count[i][j-1]){count[i][j] = count[i-1][j];direction[i][j] = 3;}else{count[i][j] = count[i][j-1];direction[i][j] = 2;}}}}for(i = 1; i <= str1_len; i++){for(j = 1; j <= str2_len; j++){printf("%d", count[i][j]);}printf("\n");}for(i = 0; i <= str1_len; i++){if(count[i][str2_len] == count[str1_len][str2_len]){display(direction, i, str2_len, str1);printf("\n");}}for(i = 0; i <= str2_len; i++){if(count[str1_len][i] == count[str1_len][str2_len]){display(direction, str1_len, i, str1);printf("\n");}}for(i = 0; i <= str1_len; i++){delete count[i];delete direction[i];}while(1);return 0;}


0 0
原创粉丝点击