zoukankan      html  css  js  c++  java
  • hdu 1159 Common Subsequence(最长公共子序列LCS)

    Problem 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.
    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.

    Sample Input

    abcfbc abfcab
    programming contest
    abcd mnp

    Sample Output

    4
    2
    0

    解题思路:基础dp!求两个字符串的最长公共子序列的长度,则dp[i][j]表示字符串s1的前i个字符与字符串s2的前j个字符构成的最长公共子序列的长度,推导式:当s1的第i个字符与s2的第j个字符相等时,dp[i][j]=dp[i-1][j-1]+1;否则dp[i][j]=max(dp[i-1][j],dp[i][j-1]),表示当前的dp[i][j]为s1的前i-1个字符与s2的前j个字符组成的最长公共子序列的长度即dp[i-1][j]和s1的前i个字符与s2的前j-1个字符组成的最长公共子序列的长度即dp[i][j-1]这两者中的最大值。dp求解的核心就是枚举到当前字符串中的某个字符,都要枚举另外一个字符串中的每个字符,并记录当前的最优解,这样最后求得dp[len1][len2]就是LCS的长度。时间复杂度是O(nm)。

    AC代码:

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int maxn=1005;
     4 char s1[maxn],s2[maxn];int len1,len2,dp[maxn][maxn];
     5 int main(){
     6     while(cin>>(s1+1)>>(s2+1)){
     7         memset(dp,0,sizeof(dp));
     8         len1=strlen(s1+1),len2=strlen(s2+1);
     9         for(int i=1;i<=len1;i++){
    10             for(int j=1;j<=len2;j++){
    11                 if(s1[i]==s2[j])dp[i][j]=dp[i-1][j-1]+1;
    12                 else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
    13             }
    14         }
    15         cout<<dp[len1][len2]<<endl;
    16     }
    17     return 0;
    18 }
  • 相关阅读:
    【SQLite操作】SQLite下载使用教程
    【VS】编译/生成解决方案时错误 未能写入输出文件“...objDebugxxx.exe”--“另一个程序正在使用此文件,进程无法访问
    Webstorm 快速补全
    JS 之循环 应用案例1
    elementUI的el-input和el-select宽度 一致
    SpringMVC 参数中接收之一 List
    VUE 之_this.da 和 this
    CSS 格式 设置标签间距 和 input slot
    Spring最简单构建一个后台{msg:"登录成功",code:200,data:null}
    VUE SpringCloud 跨域资源共享 CORS 详解
  • 原文地址:https://www.cnblogs.com/acgoto/p/8901945.html
Copyright © 2011-2022 走看看