LCS 求最长公共子序列
Posted xbqdsjh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LCS 求最长公共子序列相关的知识,希望对你有一定的参考价值。
最长公共子序列不需要字符连续出现和字串不同
//LCS 求最长公共子串模板题
Common Subsequence
描述
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, ..., xm> another sequence Z = <z1, z2, ..., zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, ..., ik> of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = <a, b, f, c> is a subsequence of X = <a, b, c, f, b, c> with index sequence <1, 2, 4, 6>. Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.
输入
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
输出
For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.
样例输入
abcfbc abfcab
programming contest
abcd mnp
样例输出
4
2
0
#include<bits/stdc++.h> using namespace std; string a,b; int dp[1001][1001], len1, len2; void lcs(int i,int j) for(i=1; i<=len1; i++) for(j=1; j<=len2; j++) if(a[i-1] == b[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j],dp[i][j-1]); int main() while(cin>>a) cin>>b; memset(dp, 0, sizeof(dp)); len1 = a.length(); len2 = b.length(); lcs(len1, len2); cout<<dp[len1][len2]<<endl;
//有可能遇到爆内存的情况,在只求长度的情况下可以把dp数组改为只有两个状态;
void lcs(int i,int j) for(i=1; i<=len1; i++) e^=1; //切换e为1 和 0; for(j=1; j<=len2; j++) if(a[i-1] == b[j-1]) dp[e][j] = dp[e^1][j-1] + val[a[i-1]]; else dp[e][j] = max(dp[e^1][j],dp[e][j-1]);
//输出最长公共子串上面的代码不变,根据dp数组状态来决定取哪几个元素
#include<bits/stdc++.h> using namespace std; string a,b; int dp[1001][1001], len1, len2; void lcs(int i,int j) for(i=1; i<=len1; i++) for(j=1; j<=len2; j++) if(a[i-1] == b[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j],dp[i][j-1]); void printflcs() char c[1001]; memset(c, 0, sizeof(c)); int i = len1;int j = len2;int d=0; while(i!=0 && j!=0) if(a[i-1] == b[j-1]) c[d++] = a[--i]; j--; else if(dp[i-1][j] < dp[i][j-1]) j--; else if(dp[i][j-1] <= dp[i-1][j]) i--; for(i=d-1; i>=0; i--) cout<<c[i]; cout<<endl; int main() while(cin>>a) cin>>b; memset(dp, 0, sizeof(dp)); len1 = a.length(); len2 = b.length(); lcs(len1, len2); printflcs(); cout<<dp[len1][len2]<<endl;
以上是关于LCS 求最长公共子序列的主要内容,如果未能解决你的问题,请参考以下文章