小单刷题笔记之dp 状态转移方程
描述
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = another sequence Z = is a subsequence of X if there exists a strictly increasing sequence of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = is a subsequence of X = with index sequence . 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 the std input. Each data set in the input 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 abfcabprogramming contest abcd mnp
样例输出
420
#include#includeusing namespace std;char sz1[1000];char sz2[1000];int maxlen[1000][1000];//maxlen[i][j]表示 字符串1左边i个和字符串2左边j个的最长公共子序列 int main(){while(cin>>sz1>>sz2){int length1=strlen(sz1);int length2=strlen(sz2);int nTmp;int i,j;for(int i=0;i<=length1;++i){maxlen[i][0]=0;}for(int j=0;j<=length2;++j)maxlen[0][j]=0;for(i=1;i<=length1;i++){for(j=1;j<=length2;j++){if(sz1[i-1]==sz2[j-1]){maxlen[i][j]=maxlen[i-1][j-1]+1;}else{maxlen[i][j]=max(maxlen[i][j-1],//重要部分maxlen[i-1][j]);}}}cout<<maxlen[length1][length2]<<endl;}return 0;}
这道题难点就是 想出if(sz1[i-1]!=sz2[i-1]) maxlen[i][j]=max(maxlen[i-1][j],maxlen[j][i-1])这一步,这一步想出来就基本就完成了,重要的是学习dp的思想:
分解子问题->具备最优子机构->无后效性
后求出状态转移方程