首页 > 代码库 > Common Subsequence

Common Subsequence

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, x ij = 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.
Input
The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.
Output
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.
Sample Input
abcfbc         abfcab
programming    contest 
abcd           mnp
Sample Output
4
2
0

求两个字符串的最长公共子序列。

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;

char a[5000];
char b[1050];
char c[1050];
int dp[1050][1050]={0};

int main()
{
    while(scanf("%s %s",b,c)!=EOF)
    {
    memset(dp,0,sizeof(dp));
    int i;
   /* for(i=0;a[i]>=‘a‘&&a[i]<=‘z‘;i++)
        b[i]=a[i];
    b[i]=‘\0‘;
    int l=0;
    for(;a[i]!=‘\0‘;i++)
        if(a[i]>=‘a‘&&a[i]<=‘z‘)
            c[l++]=a[i];
    c[l]=‘\0‘;*/
    for(i=0;c[i]!=\0;i++)
        if(c[i]==b[0])
        {
            dp[i][0]=1;
            break;
        }
    for(;c[i]!=\0;i++)
        dp[i][0]=1;
     for(i=0;b[i]!=\0;i++)
        if(c[0]==b[i])
        {
            dp[0][i]=1;
            break;
        }
    for(;b[i]!=\0;i++)
        dp[0][i]=1;
    for(int i=1;b[i]!=\0;i++)
    {
        for(int j=0;c[j]!=\0;j++)
        {
            if(c[j]==b[i])
            {
                dp[j][i]=max(dp[j-1][i-1]+1,dp[j][i-1]);
            }
            else
                dp[j][i]=max(dp[j-1][i],dp[j][i-1]);
        }
    }
    int l1=strlen(b);
    int l2=strlen(c);
    printf("%d\n",dp[l2-1][l1-1]);
    }
    return 0;
}

 

Common Subsequence