日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HDU1159(dp最长公共子序列)

發布時間:2025/3/21 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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位置的值,保留最大的賦給當前位置。這樣一直遞推到兩個字符串結束,最后一個位置存的必定為最長。

#include<cstdio> #include<cstring> int Max(int x, int y) {if(x > y)return x;elsereturn y; } int main() {int dp[500][500];char a[500];char b[500];while(~scanf("%s%s", a, b)){memset(dp, 0, sizeof(dp));for(int i = 0; i < strlen(a) + 1; ++i)for(int j = 0; j < strlen(b) + 1; ++j){if(i == 0 || b == 0)continue;if(a[i - 1] == b[j - 1])dp[i][j] = dp[i - 1][j - 1] + 1;elsedp[i][j] = Max(dp[i - 1][j], dp[i][j - 1]);}/* for(int i = 0; i <= strlen(a) + 1; ++i){for(int j = 0; j <= strlen(b) + 1; ++j)printf("%d ", dp[i][j]);printf("\n");}*/printf("%d\n", dp[strlen(a)][strlen(b)]);}return 0; }

總結

以上是生活随笔為你收集整理的HDU1159(dp最长公共子序列)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。