• ACM 最大公共子序列


    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, 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 <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    int const N=1000;
    int save[N][N];
    char str1[N],str2[N];
    int max(int x,int y)
    {
    	return x>y?x:y;
    }
    int maxlen(char *str1,char *str2)
    {
        int n1=strlen(str1),n2=strlen(str2),i,j;
        for(i=0;i<=max(n1,n2);i++)
            save[i][0]=save[0][i]=0;
        for(i=1;i<=n1;i++)
            for(j=1;j<=n2;j++)   //以下从str1[0]和str2[0]开始比较
                save[i][j]=(str1[i-1]==str2[j-1] ? save[i-1][j-1]+1 : max(save[i-1][j],save[i][j-1]));
        return save[n1][n2];
    }
    
    int main()
    {
    	while(scanf("%s%s",str1,str2)!=EOF)
    	{
    		memset(save,0,sizeof(save));
    		cout<<maxlen(str1,str2)<<endl;
    	}
    	return 0;
    }
    
    
    

      



  • 相关阅读:
    软件工程结对作业02
    最大子数组和
    四则运算2单元测试
    软件工程个人作业03
    梦断代码阅读笔记01
    最大值的单元测试
    构建之法阅读笔记01
    进度条记录02
    软件工程个人作业02
    【BZOJ2595_洛谷4294】[WC2008]游览计划(斯坦纳树_状压DP)
  • 原文地址:https://www.cnblogs.com/xinxiangqing/p/4730947.html
Copyright © 2020-2023  润新知