zoukankan      html  css  js  c++  java
  • Poj 1458 Common Subsequence(LCS)

    一、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.

    二、题解
            这题和之前做的poj 1159 的解法相同,都是用到了动态规划解LCS算法。详情请看1159.本来这道题应该很容易就解出来的,但是由于BBS上的数据错误,害我以为不是LCS,但是这个题目的定义就是LCS的形式化定义,所以纠结了一阵。后来发现原来是数据的错误。
    三、Java代码
        import java.util.Scanner;   
          
        public class Main {   
            public static int LCS(String x,String y){  
                short [][] z=new short [x.length()+1][y.length()+1];  
                short i,j;  
                for( i=0;i<=x.length();i++)  
                    z[i][0]=0;  
                for( j=0;j<=y.length();j++)  
                    z[0][j]=0;  
                  
                for(i=1;i<=x.length();i++){  
                    for( j=1;j<=y.length();j++){  
                        if(x.charAt(i-1)==y.charAt(j-1)){  
                            z[i][j]= (short) (z[i-1][j-1]+1);  
                        }  
                        else  
                            z[i][j]=z[i-1][j] > z[i][j-1] ?z[i-1][j]:z[i][j-1];  
                    }  
                }  
                return z[x.length()][y.length()];  
            }  
            public static void main(String[] args) {   
               Scanner cin = new Scanner(System.in); 
               while(cin.hasNext()){
               System.out.println(LCS(cin.next(),cin.next()));
               }   
            }
          }   


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Ubuntu 16.04 compare 软件安装
    ubuntu 18 常用软件安装
    LSTM时间序列预测学习
    ubuntu 16.04 屏幕截图
    ubuntu 16.04 tensorboard 学习
    ubuntu 16 .04常见指令整理
    ABAP 更改销售订单(BAPI'BAPI_SALESORDER_CHANGE')
    ABAP SM30表维护生成器,新加一列描述仅供用户维护时参考,不存内表。(例如物料描述,客户描述)
    93年到底多少岁
    一个93年的中年人对2019年的总结
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734162.html
Copyright © 2011-2022 走看看