10405 - Longest Common Subsequence

来源:互联网 发布:java temp 目录 编辑:程序博客网 时间:2024/06/09 17:53

Problem C: Longest Common Subsequence

Sequence 1:                

Sequence 2:                


Given two sequences of characters, print the length of the longest common subsequence of both sequences. For example, the longest common subsequence of the following two sequences:

abcdghaedfhr
is adh of length 3.

Input consists of pairs of lines. The first line of a pair contains the first string and the second line contains the second string. Each string is on a separate line and consists of at most 1,000 characters

For each subsequent pair of input lines, output a line containing one integer number which satisfies the criteria stated above.

Sample input

a1b2c3d4ezz1yy2xx3ww4vvabcdghaedfhrabcdefghijklmnopqrstuvwxyza0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0abcdefghijklmnzyxwvutsrqpoopqrstuvwxyzabcdefghijklmn

Output for the sample input

432614

Problem Setter: Piotr Rudnick

i

/*比较简单的一道动态规划,可称为是水体,具体的思想是:查找相同时,dp[i][j]=dp[i-1][j-1]+1;不同时就比较,dp[i][j]=max(d[i][j-1],d[i-1][j]);*/#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int N=1005;int dp[N][N];char str1[N],str2[N];int len1,len2;void DP(){int i,j;for(i=0;i<len2;i++){for(j=0;j<len1;j++){if(str1[j]==str2[i]){if(i-1<0||j-1<0)//越界{dp[i][j]=1;}else{dp[i][j]=dp[i-1][j-1]+1;}}else{if(i-1<0&&j-1<0)//越界{dp[i][j]=0;}else if(i-1<0&&j-1>=0)//越界{dp[i][j]=dp[i][j-1];}else if(i-1>=0&&j-1<0)//越界{dp[i][j]=dp[i-1][j];}else {dp[i][j]=dp[i][j-1]>dp[i-1][j]?dp[i][j-1]:dp[i-1][j];}}}}}int main(){while(gets(str1)!=NULL){gets(str2);memset(dp,0,sizeof(dp));len1=strlen(str1);len2=strlen(str2);DP();cout<<dp[len2-1][len1-1]<<endl;}return 0;}


0 0
原创粉丝点击