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 }
  • 相关阅读:
    javascript学习笔记(一):基础、输出、注释、引用、变量、数据类型
    black-hole《XSS的原理分析与解剖》阅读笔记
    《xss跨站脚本剖析与防御》实验笔记
    XSS和CSRF的区别
    前端常用插件、工具类库汇总(下)
    前端常用插件、工具类库汇总(上)
    前端特效【第03期】|果汁混合效果-上
    玩转 React 【第03期】:邂逅 React 组件
    前端修炼の道 | 如何成为一名合格前端开发工程师?
    前端特效【第02期】|多功能提交按钮
  • 原文地址:https://www.cnblogs.com/acgoto/p/8901945.html
Copyright © 2011-2022 走看看