Hangzhou Electric 1159 (Common subsequence) LCS and DP

Source: Internet
Author: User

Click to open Hangzhou electric 1159

Problem Descriptiona 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 E Xists a strictly increasing sequence <i1, I2, ..., ik> of indices of X such so for all J =,..., K, Xij = ZJ. For example, Z = <a, B, F, c> are a subsequence of X = <a, B, C, F, B, c> with index sequence <1, 2, 4, 6&gt ;. Given sequences X and y the problem is to find the length of the Maximum-length common subsequence of x and Y.
The program input was from a text file. Each data set in the file contains the strings representing the given sequences. The sequences is separated by any number of white spaces. The input data is correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from th e beginning of a separate line.

Sample Input
ABCFBC abfcabprogramming contest ABCD MNP

Sample Output
420


Code implementation:

Import Java.util.*;class main {static int[][] dp;public static void Main (string[] args) {Scanner sc=new Scanner (system.in) ; while (Sc.hasnext ()) {String str1=sc.next (); String Str2=sc.next (); LCS (STR1,STR2); System.out.println (Dp[str1.length ()][str2.length ());}} public static void LCS (String str1,string str2) {int i,j;dp=new int[str1.length () +1][str2.length () +1];for (i=1;i<= Str1.length (); i++) {for (J=1;j<=str2.length (); j + +) {if (Str1.charat (i-1) ==str2.charat (j-1)) {dp[i][j]=dp[i-1][ j-1]+1;} Else{dp[i][j]=math.max (Dp[i-1][j], dp[i][j-1]);}}}}



Hangzhou Electric 1159 (Common subsequence) LCS and DP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.