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

  • 相关阅读:
    Button 样式设置
    WPF 运行报错:在使用 ItemsSource 之前,项集合必须为空。
    c# List 按条件查找、删除
    c# WPF DataGrid设置一列自增一
    C# WPF DataGrid去掉最左侧自动生成一列
    int 转换成定长的 byte数组
    字节数组 byte[] 与 int型数字的相互转换
    [ c# ] int 类型转换为固定长度的字符串
    ListView 绑定 字典
    不能引用的文件,却需要在程序底层使用的文件 的存放位置
  • 原文地址:https://www.cnblogs.com/Leozi/p/13281242.html
Copyright © 2011-2022 走看看