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()));
               }   
            }
          }   


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

  • 相关阅读:
    极客技术专题【011期】:EasyUI初级教程
    帮助自定义选择框样式的Javascript
    利用HTML5与jQuery技术创建一个简单的自动表单完成
    30个iPhone健康应用帮助你保持身体健康
    如何构建下拉滑动式响应导航菜单
    推荐十款来自极客标签的超棒前端特效[第十三期]
    重新设计网站的10点建议
    创建CSS3警示框渐变动画
    17种新型的响应式开发框架
    使用jQuery创建模态窗口登陆效果
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734161.html
Copyright © 2011-2022 走看看