Describe:
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 E Xists a strictly increasing sequence <i1, I2, ..., ik> of indices of X such so for all J =,..., K, Xij = ZJ. For example, Z = <a, B, F, c> are a subsequence of X = <a, B, C, F, B, c> with index sequence <1, 2, 4, 6> ;. Given sequences X and y the problem is to find the length of the Maximum-length common subsequence of x and Y.
The program input was from a text file. Each data set in the file contains the strings representing the given sequences. The sequences is separated by anynumber of white spaces. The input data is correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from th e beginning of a separate line.
Code:
The longest common subsequence sequence x={x1,x2,..., xm} and Y={y1,y2,..., yn} is z={z1,z2,..., ZK}, then
(1) If Xm=yn, then Zk=xm=yn, and Zk-1 is the longest common subsequence of xm-1 and yn-1.
(2) If Xm≠yn and ZK≠XM, then Z is the longest common subsequence of xm-1 and Y.
(3) If Xm≠yn and Zk≠yn, then Z is the longest common sub-sequence of x and yn-1.
#include <stdio.h>#include<string.h>#include<iostream>#include<stdlib.h>#include<math.h>using namespacestd;#defineN 1000intMain () {CharX[n],y[n]; intDp[n][n]; while(SCANF ("%s%s", &x,&y)! =EOF) { //Tle:memset (Dp,0,sizeof (DP)); for(intI=0; i<n;i++) {dp[0][i]=0;DP [i][0]=0; } for(intI=1; I<=strlen (x); i++ ){ for(intj=1; J<=strlen (y); J + + ){ if(x[i-1]==y[j-1]) Dp[i][j]=dp[i-1][j-1]+1; ElseDp[i][j]=max (dp[i-1][j],dp[i][j-1]); }} printf ("%d\n", Dp[strlen (x)][strlen (y)]); } System ("Pause"); return 0;}
Hdu1159-common subsequence