經典的最長公共子串行問題。
狀態轉移方程為 :
if(x[i] == y[j]) dp[i, j] = dp[i - 1, j - 1] +1else dp[i, j] = max(dp[i - 1], j, dp[i, j - 1]);
設有字串x和字串y,dp[i, j]表示的是x的前i個字元與y的前j個字元的最長公共子串行長度。
如果x[i] == y[j] ,那麼這個字元與之前的lcs 一定可以構成乙個新的lcs;
如果x[i] != y[j] ,則分別考察 dp[i -1][j], 和dp[i, j - 1],選擇其中的較大者為lcs。
source code:
//#pragma comment(linker, "/stack:16777216")
//for c++ compiler
#include #include
#include
#include
#include
#include
#include
#include
#define ll long long
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define abs(x) (((x) > 0) ? (x) : (-(x)))
using
namespace
std;
const
int inf = 0x3f3f3f3f
;const
int maxn = 500
;int
dp[maxn][maxn];
intmain()
else}}
cout
<< dp[len1][len2] <}
return0;
}
poj 1458 最長公共子串行
common subsequence 題意 一行給出兩個字串s1和s2,找出他們的最長 公共子串行數量,乙個金典的動態規劃問題。用dp i j 表示字串s1取前i個,字串s2取前j個時,他們的最長公共子串行數量有多少。當s2右端又加入了乙個字元時,即表示為dp i j 1 時,如果s1 i 和s2 ...
POJ1458最長公共子串行
為了完成poj中的一題 spell checker 要寫乙個最長公共子串行的程式,居然突然全給忘了,楞是沒有寫出來,深深的鄙視自己一下。這也是一道動態規劃的典型題。遞迴實現如下 poj提交會超時,但是確實可以實現 using namespace std define max a b a b a b ...
POJ 1458 最長公共子串行
這個題的意思就是說 給乙個序列 a 和 b 讓你求他們的共同的子串行的長度,這些子串行可以不在原來的字串中連續排列。這個題的話,我們可以使用動態規劃的思路,我們假設 maxlen i j 是 a 串和 b 串中從一開始的,a 串中的的第 i 個字元和b 串中的第 j 個字元的最長公共子串行的長度。我...