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


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

  • 相关阅读:
    Python:如何显示进度条
    Python:常用函数封装
    Javascript:常用函数封装
    Javascript:alert(1)可以这样写以绕过filter
    SQL注入备忘单
    Web渗透:PHP字符编码绕过漏洞总结
    SQLi Lab的视频教程和文字教程
    Python:使用基于事件驱动的SAX解析XML
    Python:渗透测试开源项目【源码值得精读】
    Python:SQLMap源码精读—start函数
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734162.html
Copyright © 2011-2022 走看看