zoukankan      html  css  js  c++  java
  • POJ-1458 Common Subsequence (最长公共子序列)

    Common Subsequence
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 39851   Accepted: 16030

    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.

    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
    大致题意:求两个字符串的最长公共子序列的长度。

    思路:这是一个很经典的最长公共子序列(LCS)问题。动态转移方程式如下,设有字符串X和字符串Y,dp[i,j]表示的是X的钱i个字符与Y的钱j个字符的最长公共子序列的长度。如果X[i]==Y[j],那么这个字符与之前的LCS一定可以构成一个新的LCS;如果X[i]!=Y[j],则分别考查dp[i-1,j]和dp[i][j-1],选择其中的较大者为LCS。


     1 #include<iostream>
     2 #include<cstdio>
     3 #include<algorithm>
     4 #include<cmath>
     5 #include<string>
     6 using namespace std;
     7 const int MAX = 500;
     8 int dp[MAX][MAX] ={0};
     9 int main()
    10 {
    11     int len1,len2;
    12     string str1,str2;
    13     while(cin>>str1>>str2)
    14     {
    15         len1=str1.length();
    16         len2=str2.length();
    17         for(int i=1;i<=len1;i++)
    18         {
    19             for(int j=1;j<=len2;j++)
    20             {
    21                 if(str1[i-1]==str2[j-1])
    22                 {
    23                     dp[i][j]=dp[i-1][j-1]+1;
    24                 }
    25                 else
    26                 {
    27                     dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
    28                 }
    29             }
    30         }
    31         cout<<dp[len1][len2]<<endl;
    32     }
    33     return 0;
    34 }
  • 相关阅读:
    jxl导入/导出excel
    iText导出pdf、word、图片
    Java CSV操作(导出和导入)
    Spring3.0+Hibernate+Atomikos集成构建JTA的分布式事务--解决多数据源跨库事务
    jQuery插件:跨浏览器复制jQuery-zclip
    微信小程序之表单提交
    微信小程序只之全局存储
    微信小程序之工具js封装与使用
    重构的艺术 深入认识
    重构的素养
  • 原文地址:https://www.cnblogs.com/caterpillarofharvard/p/4225815.html
Copyright © 2011-2022 走看看