zoukankan      html  css  js  c++  java
  • HDU-1159 Common Subsequence

    Time limit 1000ms Memory limit 32768kB

    题目:

    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.
    The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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.

    输入:

    abcfbc abfcab

    programming contest

    abcd mnp

    输出:

    4

    2

    0

    题意:给定两个字符串,找出最长公共子序列(LCS)。

    思路:最长公共子序列的模板题,用个二维dp数组记录第一个字符串的前i个字符,第二个字符串的前j个字符,dp[i][j]就表示第一个字符串的前i个字符和第二个字符串的前j个字符的最长公共子序列。从两个字符串的第一个字符开始比较,如果相同,dp[i][j]=dp[i-1][j-1]+1;如果不同,dp[i][j]=max{dp[i-1][j],dp[i][j-1]}。

    AC代码:

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    const int p=1005;
    int c[p][p];
    int main()
    {
        int m,n;
        char a[p],b[p];
        while(scanf("%s %s",(a+1),(b+1))!=EOF)
        {
        memset(c,0,sizeof(c));
        m=strlen(a+1);
        n=strlen(b+1);
        for(int i=1;i<=m;i++)
            for(int j=1;j<=n;j++)
        {
              if(a[i]==b[j])
                c[i][j]=c[i-1][j-1]+1;
              else
                c[i][j]=max(c[i-1][j],c[i][j-1]);
        }
        cout<<c[m][n]<<endl;
        }
    }

    注意:

    输入字符串从地址1开始,不要从地址0开始输入,因为后面要用到i-1和j-1,注意数组得清零和边界。

  • 相关阅读:
    团队沟通利器之UML——活动图
    Ninject对Web Api的支持问题
    关于分布式系统的数据一致性问题
    ASP.NET Web开发框架 查询
    用泛型的IEqualityComparer<T> 去除去重复项
    数据库连接监控组件,避免日常开发中因为数据库连接长时间占用或业务完成后忘记关闭连接所带来的数据库问题
    认识项目经理
    状态模式(State Pattern)
    Django框架学习通用视图
    MS CRM 2011 Schedule Service Activities
  • 原文地址:https://www.cnblogs.com/Leozi/p/13281242.html
Copyright © 2011-2022 走看看