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,注意数组得清零和边界。

  • 相关阅读:
    一文梳理Ubuntu下Eigen矩阵运算库总结教程
    Ubuntu下安装与使用Eigen矩阵运算库教程
    Ubuntu下cmake教程实践从入门到会用
    collection of vim vim tutorial for beginner
    利用ipython实现多线程
    如何快速地从mongo中提取数据到numpy以及pandas中去
    Git Push 避免用户名和密码方法
    如何使用scikit—learn处理文本数据
    format格式
    fk输入地壳模型容易出错的地方
  • 原文地址:https://www.cnblogs.com/Leozi/p/13281242.html
Copyright © 2011-2022 走看看