1.题目编号:1002
2.简单题意:给出两个子串,依次比较子串得到两个子串相等的字符的最大长度,即最长公共子序列。
3.解题思路形成过程:在动态规划的专题,就想到用动态规划的方法去做,首先要找子问题,假设有两个字符串a=a0,a1,a2,...am-1,b=b0,b1,b2...bn-1。如果am-1==bn-1,则当前最长公共子序列为a0,a1,...am-2与b0,b1,b2...bn-2的最长公共子序列的长度加1;如果am-1!=bn-1,则最长公共子序列为max(a0,a1,...am-2与b0,b1,b2...bn-1的公共子序列,a0,a1...am-1和b0,b1,b2...bn-2的子序列)就得到递归表示: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]);}
4.感悟:这种题就像是模板,一个会了,只要遇到题就想着找状态转移方程组=.=
5.AC的代码:
#include<iostream>
#include<cstring>
using namespace std;
char a[1000];
char b[1000];
int dp[1000][1000];
int max(int l,int s){
if (l>=s)
return l;
else
return s;
}
int main(){
while(cin>>a>>b){
int a1=strlen(a);
int b1=strlen(b);
memset(dp,0,sizeof(dp));
for(int i=1;i<a1+1;i++){
for(int j=1;j<b1+1;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]);
}
}
}
cout<<dp[a1][b1]<<endl;
}
return 0;
}
原题:
Problem Description
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. <br>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. <br>
Sample Input
abcfbc abfcab programming contest abcd mnp
Sample Output
4 2 0