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


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

  • 相关阅读:
    BZOJ1076 [SCOI2008]奖励关 概率 状态压缩动态规划
    BZOJ1040 [ZJOI2008]骑士 基环树林(环套树) 树形动态规划
    洛谷1623 树的匹配 树形动态规划 高精度
    BZOJ1053 [HAOI2007]反素数ant 数论
    Vijos1906 联合权值 NOIP2014Day1T2 树形动态规划
    网络流24题 第五题
    网络流24题 第四题
    网络流24题 第三题
    网络流24题 第二题
    网络流24题 第一题
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734162.html
Copyright © 2011-2022 走看看