练习三1002

来源:互联网 发布:帝国cms模板安装教程 编辑:程序博客网 时间:2024/05/16 17:40

Problem B
Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 85   Accepted Submission(s) : 34
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 abfcabprogramming contest abcd mnp
 

Sample Output
420
题意:给出两串字母,计算这两串字母中相同且顺序增加的字母的个数。
思路:从第一串的第一个开始,和第二串的字母比较,如果相同加1,否则到这个位置时的结果为前面中最大的(这个地方想起来较困难)。
代码:
#include<iostream>#include<cstring>#include<string.h>using namespace std;int max(int x,int y){return x>y?x:y;}int main(){char a[1000],b[1000];int dp[1000][1000],m,n;while(cin>>a>>b){m=strlen(a);n=strlen(b);memset(dp,0,sizeof(dp));for(int i=0;i<m;i++){for(int j=0;j<n;j++){if(a[i]==b[j])dp[i+1][j+1]=dp[i][j]+1;elsedp[i+1][j+1]=max(dp[i+1][j],dp[i][j+1]);}}cout<<dp[m][n]<<endl;memset(a,0,sizeof(a));memset(b,0,sizeof(b));}return 0;}
0 0