noi 2 6 1808 最長公共子串行(DP)

2022-07-23 02:18:11 字數 557 閱讀 2453

題意:給2個字串求其最大公共子串行的長度。

解法:這個和一般的狀態定義有點不一樣,f[i][j]表示 str 前i位和 str2 前j的最大公共子串行的長度,而不是選 str 的第i位和 str2 的第j位。

仔細想想就可以知道只表示「前...」的狀態可以保證每次拓展答案時,之前的狀態已經保證了「公共」,因此str[i]==str2[j]時f+1也不會錯。

1 #include2 #include3 #include4 #include5

using

namespace

std;67

const

int l=210;8

intf[l][l];

9char

str[l],str2[l];

1011

int mmax(int x,int y)

12int

main()

1324 printf("

%d\n

",f[len][len2]);25}

26return0;

27 }

最長公共子串行 最長公共子串

1 最長公共子串行 採用動態規劃的思想,用乙個陣列dp i j 記錄a字串中i 1位置到b字串中j 1位置的最長公共子串行,若a i 1 b j 1 那麼dp i j dp i 1 j 1 1,若不相同,那麼dp i j 就是dp i 1 j 和dp i j 1 中的較大者。class lcs el...

最長公共子串行 最長公共子串

1.區別 找兩個字串的最長公共子串,這個子串要求在原字串中是連續的。而最長公共子串行則並不要求連續。2 最長公共子串 其實這是乙個序貫決策問題,可以用動態規劃來求解。我們採用乙個二維矩陣來記錄中間的結果。這個二維矩陣怎麼構造呢?直接舉個例子吧 bab 和 caba 當然我們現在一眼就可以看出來最長公...

最長公共子串 最長公共子串行

子串要求連續 子串行不要求連續 之前的做法是dp求子序列 include include include using namespace std const int inf 0x3f3f3f3f const int mod 1000000007 string s1,s2 int dp 1010 10...