专题三 第十二题

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 = &lt;x1, x2, ..., xm&gt; another sequence Z = &lt;z1, z2, ..., zk&gt; is a subsequence of X if there exists a strictly increasing sequence &lt;i1, i2, ..., ik&gt; of indices of X such that for all j = 1,2,...,k, xij = zj. For example, Z = &lt;a, b, f, c&gt; is a subsequence of X = &lt;a, b, c, f, b, c&gt; with index sequence &lt;1, 2, 4, 6&gt;. 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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值