zoukankan      html  css  js  c++  java
  • poj_1458 LCS problem F.最长上升公共子序列

    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, 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
     分析:
    d[i][j]表示a[1],a[2]……a[i] 和b[1],b[2]……b[i]的最长上升子序列长度.while(a[i]==a[j])  d[i][j]=d[i-1][j-1]+1;   else  d[i][j]=max{d[i-1][j],d[i][j-1]};     时间复杂度为o(n*m).
     
    代码及简要分析:
     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<string>   //使用cin>>输入需要加上此头文件
     5 using namespace std;
     6 string a,b;
     7 int dp[1000][1000];
     8 int max(int x,int y)
     9 {
    10     if(x>=y)
    11         return x;
    12     else
    13         return y;
    14 }
    15 
    16 int main()
    17 {
    18     int i,j;
    19     while(cin>>a)
    20     {
    21         cin>>b;
    22         memset(dp,0,sizeof(dp));//ddp[i][j]为a[0]...a[i]和b[0]...b[j]的最长公共子序列的长度。
    23         for(i=0;i<a.size();i++)
    24         {
    25             for(j=0;j<b.size();j++)
    26             {
    27                 if(a[i]==b[j])
    28                     dp[i+1][j+1]=dp[i][j]+1;  //注意此从 dp[1][1]开始
    29                 else
    30                     dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
    31 
    32             }
    33         }
    34         printf("%d
    ",dp[i][j]);
    35     }
    36    return 0;
    37 }
    View Code
     
  • 相关阅读:
    Spring入门第二十九课
    Spring入门第二十八课
    Spring入门第二十七课
    Spring入门第二十六课
    Spring入门第二十五课
    Spring入门第二十四课
    Spring入门第二十三课
    Spring入门第二十二课
    Spring入门第二十一课
    Spring入门第二十课
  • 原文地址:https://www.cnblogs.com/x512149882/p/4738706.html
Copyright © 2011-2022 走看看