1. 程式人生 > >poj~最長公共子序列和最長公共子串

poj~最長公共子序列和最長公共子串

最長公共子序列
poj1458
問題描述

給出兩個字串,求出這樣的一個最長的公共子序列的長度:
子序列中的每個字元都能在兩個原串中找到,
而且每個字元的先後順序和原串中的先後順序一致。

Sample Input

abcfbc abfcab

programming contest

abcd mnp

Sample Output

4

2

0

問題分析
輸入兩個串s1,s2,
設MaxLen(i,j)表示:
s1的左邊i個字元形成的子串,與s2左邊的j個字元形成的子串的最長公共子序列的長度(i,j從0開始算)
MaxLen(i,j) 就是本題的“狀態”
假定 len1 = strlen(s1),len2 = strlen(s2)
那麼題目就是要求 MaxLen(len1,len2)
顯然:
MaxLen(n,0) = 0 ( n= 0…len1)
MaxLen(0,n) = 0 ( n=0…len2)
遞推公式:
if ( s1[i-1] == s2[j-1] ) //s1的最左邊字元是s1[0]
MaxLen(i,j) = MaxLen(i-1,j-1) + 1;
else
MaxLen(i,j) = Max(MaxLen(i,j-1),MaxLen(i-1,j) );
時間複雜度O(mn) m,n是兩個字串長度
這裡寫圖片描述


S1[i-1]!= s2[ j-1]時,MaxLen(S1,S2)不會比MaxLen(S1,S2j-1)
和MaxLen(S1i-1,S2)兩者之中任何一個小,也不會比兩者都大。
所以是等於MaxLen(S1,S2j-1)和MaxLen(S1i-1,S2)兩者之中大的那個。
AC程式碼

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
char str1[10000],str2[10000];
int maxLen[10000][10000];
int main()
{
    while
(cin>>str1>>str2) { int len1=strlen(str1); int len2=strlen(str2); for(int i=0;i<1000;i++) { maxLen[0][i]=0; maxLen[i][0]=0; } for(int i=1;i<=len1;i++) for(int j=1;j<=len2;j++) { if
(str1[i-1]==str2[j-1]) maxLen[i][j]=maxLen[i-1][j-1]+1; else maxLen[i][j]=max(maxLen[i-1][j],maxLen[i][j-1]); } cout<<maxLen[len1][len2]<<endl; } return 0; }