最长公共子序列(LCS):动态规划
D-LCS
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.
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.
Input
abcfbc abfcab programming contest abcd mnp
Output
4 2 0
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0
DP思路很简单,因为状态转移方程很容易找到。
我们设这两个序列a、b的长度分别为i和j,d[i][j]表示最长公共子序列的长度。
那么就有状态转移方程:
d[i][j]=max(d[i-1][j],d[i][j-1]) ,a[i]!=b[j]
d[i][j]=d[i-1][j-1]+1 ,a[i]=b[j]
把两个序列遍历一遍就可以得到d[i][j]了。
代码如下:
1 #include<iostream> 2 #include<cstring> 3 const int MAXN=1e3+1; 4 using namespace std; 5 string a,b; 6 int dp[MAXN][MAXN]; 7 int main() 8 { 9 memset(dp,0,sizeof(dp)); 10 while(cin>>a>>b) 11 { 12 int n=a.size(); 13 int m=b.size(); 14 //cout<<n<<" "<<m<<endl; 15 for(int i=0;i<n;i++) 16 { 17 for(int j=0;j<m;j++) 18 { 19 if(a[i]==b[j])dp[i+1][j+1]=dp[i][j]+1; 20 else dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]); 21 //cout<<dp[i][j]<<" "; 22 } 23 } 24 cout<<dp[n][m]<<endl; 25 } 26 }

浙公网安备 33010602011771号