最长公共子序列

来源:互联网 发布:软件开发与编程的区别 编辑:程序博客网 时间:2024/05/01 22:29

最长公共子序列

时间限制:3000 ms  |  内存限制:65535 KB
难度:3
描述
咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。
tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
输入
第一行给出一个整数N(0<N<100)表示待测数据组数
接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000.
输出
每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。
样例输入
2asdfadfsd123abcabc123abc
样例输出
36
 #include <iostream>#include <stdio.h>#include <string.h>using namespace std;int dp[1000][1000] = {0};int main(){int pre;cin>>pre;getchar();while(pre--){char str1[1000], str2[1000];scanf("%s%s", str1 + 1, str2 + 1);str1[0] = str2[0] = '#'; int len1 = strlen(str1);int len2 = strlen(str2);for(int i = 1; i < len1; i++)for(int j = 1; j < len2; j++){if(str1[i] == str2[j])dp[i][j] = dp[i - 1][j - 1] + 1;elsedp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j]: dp[i][j - 1];}cout<<dp[len1 - 1][len2 - 1]<<endl; }return 0;}        

//输出公共长度同时输出公共的序列
#include <iostream>#include <stdio.h>#include <string.h>using namespace std;int dp[1000][1000] = {0}, status[1000][1000];char str1[1000], str2[1000];void printStr(int i, int j);int main(){int pre;cin>>pre;getchar();while(pre--){memset(dp, 0, sizeof(0));memset(status, 0, sizeof(status));scanf("%s%s", str1 + 1, str2 + 1);str1[0] = str2[0] = '#';int len1 = strlen(str1);int len2 = strlen(str2);for(int i = 1; i < len1; i++)for(int j = 1; j < len2; j++){if(str1[i] == str2[j]){dp[i][j] = dp[i - 1][j - 1] + 1;status[i][j] = 0;}else if(dp[i - 1][j] >= dp[i][j - 1]){dp[i][j] = dp[i - 1][j];status[i][j] = 1;}else if(dp[i - 1][j] < dp[i][j - 1]){dp[i][j] = dp[i][j - 1];status[i][j] = 2;}}cout<<dp[len1 - 1][len2 - 1]<<endl;printStr(len1 - 1, len2 - 1);cout<<endl;}return 0;}void printStr(int i, int j){if(i == 0 || j == 0)return ;if(status[i][j] == 0){printStr(i - 1, j - 1);cout<<str1[i];}else {if(status[i][j] == 1)printStr(i - 1, j);else if(status[i][j] == 2)printStr(i, j - 1);} }


0 0