zoukankan      html  css  js  c++  java
  • POJ 1458 Common Subsequence(简单DP,LCS)

    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, x ij = 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.

    Input

    The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

    Output

    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题,最长公共子序列问题(LCS)。
    题解:

      假设有两个字符串s1s2...sn和t1t2...tm,定义dp[i][j]:=
    s1s2...si和t1t2...tj(i<=n,j<=m)。

      由此,dp[i][j]对应的公共子序列可能是如下几种情况。
      1.当s[i+1]=s[j+1]时,在s1...si和t1...tj的公共子序列的末尾加上si+1
      2.
    当s[i+1]≠s[j+1]时,s1...si和t1...tj+1的公共子序列,或者s1...si+1和t1..tj的公共子序列。

      由以上的几种情况可以得到递推关系:
        dp[i+1][j+1]=dp[i][j]+1 (s[i]==t[i])
        dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])   (其他情况)
      
     时间复杂度为O(nm),dp[n][m]就是LCS的长度。
     
    
    
    #include<iostream>
    #include<algorithm>
    #include<string>
    using namespace std;
    int dp[1001][1001];
    int main()
    {
        string a,b;
        while(cin>>a>>b)
        {
            memset(dp,0,sizeof(dp));
            int lena=a.length(),lenb=b.length();
            for(int i=1;i<=lena;i++)
                for(int j=1;j<=lenb;j++)
                {
                    if(a[i-1]==b[j-1])
                        dp[i][j]=dp[i-1][j-1]+1;
                    else
                        dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            cout<<dp[lena][lenb]<<endl;
        }
        return 0;
    }
  • 相关阅读:
    Tomcat启动报错java.net.AbstractPlainSocketImpl(java/net/AbstractPlainSocketImpl.java:178:-1)Struts在网络复杂情况下启动报错解决办法
    webpack入门级教程
    jquery-ui sortable 使用实例
    JS-类型转换
    JavaScript语言核心--词法结构
    理解CSS盒子模型
    HTML DOCTYPE 标签
    2015总结和2016计划
    MVC & MVVM
    前端常见问题汇总
  • 原文地址:https://www.cnblogs.com/orion7/p/7465067.html
Copyright © 2011-2022 走看看