HDU1159(dp最长公共子序列)
題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1159
Common Subsequence
Problem 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.
The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. 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.
Sample Input
abcfbc abfcab
programming contest
abcd mnp
Sample Output
4
2
0
題目大意:題意很簡單,就是給你兩個字符串,求他們兩個的最長公共子序列。
解題思路:比賽時遇到的一道題,硬是沒憋出來。自己的動態的規劃這方面還是很渣,看的懂題解卻用不來。下來好好學習了別人的方法,這題屬于dp中比較基礎的題。代碼也很短,但思路卻很不錯,想通了就覺得很妙,想不通就很難受。
用一個二維數組來存儲最大公共子序列的長度,一個雙重循環,來遍歷兩個串。當遇到相同字符時就把就將圖中該位置左上角的數加一賦給當前位置。如果不相同就比較i-1和j-1位置的值,保留最大的賦給當前位置。這樣一直遞推到兩個字符串結束,最后一個位置存的必定為最長。
總結
以上是生活随笔為你收集整理的HDU1159(dp最长公共子序列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: # POJ-1979(BFS)
- 下一篇: HDU-5706(DFS)