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;
    }
  • 相关阅读:
    asp.net常用的javascript经典例子
    Silverlight学习之——布局系统
    TreeView数据绑定方法
    软件测试:单元测试的一些疑问
    Silverlight学习之——Deep Zoom文件格式概述
    把生活节奏调整得慢一点
    20、Windows内核函数(1)Windows驱动开发详解笔记,字符串
    24、Windows派遣函数(2)Windows驱动开发详解笔记,直接读写方式
    21、Windows内核函数(2)Windows驱动开发详解笔记,文件操作
    27、Windows内核编程,IRP的同步(1)
  • 原文地址:https://www.cnblogs.com/orion7/p/7465067.html
Copyright © 2011-2022 走看看