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


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

  • 相关阅读:
    Android6.0-运行时权限处理
    Notification的基本用法以及使用RemoteView实现自定义布局
    Android Apk的反编译和加密
    SurfaceView的基本使用
    Java8部分新特性的学习
    Android的UI调优
    Builder模式详解及其在Android开发中的应用
    hex(x) 将整数x转换为16进制字符串
    oct(x) 将一个数字转化为8进制
    sum(iterable[, start]) 对集合求和
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734162.html
Copyright © 2011-2022 走看看