Common Subsequence

             Common Subsequence

Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u

 

Description

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, xij = 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

解析:

 

题目描述:
 
给定2个序列X={x1,x2,…,xm}和Y={y1,y2,…,yn},找出X和Y的最长公共子序列
 
分析:
 
设序列X={x1,x2,…,xm}和Y={y1,y2,…,yn}的最长公共子序列为Z={z1,z2,…,zk} ,则 (1)若xm=yn,则zk=xm=yn,且zk-1是xm-1和yn-1的最长公共子序列。 (2)若xm≠yn且zk≠xm,则Z是xm-1和Y的最长公共子序列。 (3)若xm≠yn且zk≠yn,则Z是X和yn-1的最长公共子序列。
 
状态转移方程:
 
c[i][j] 记录序列和的最长公共子序列的长度。其中, Xi={x1,x2,…,xi};Yj={y1,y2,…,yj}
 
 

# include<stdio.h>
# include<string.h>
char str1[1000],str2[1000];
int dp[1000][1000];
int max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    int i,j,len1,len2;
    while(scanf("%s %s",&str1[1],&str2[1])!=EOF)//由于循环从1开始,就这样输入,学习一下这种输入方法
    {
        len1=strlen(&str1[1]);
        len2=strlen(&str2[1]);
        memset(dp,0,sizeof(dp));
        for(i=1;i<=len1;i++)
        {
            for(j=1;j<=len2;j++)
            {
                if(str1[i]==str2[j])
                {
                    dp[i][j]=dp[i-1][j-1]+1;
                }
                else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        }
        printf("%d\n",dp[len1][len2]);
    }
        return 0;
}

 

 

posted on 2012-08-19 10:42  即为将军  阅读(202)  评论(0)    收藏  举报

导航